I am new in iOS programming. I have an Android app that use c library. I want to create same iOS app and use same library. I search about it but most of results are for objective-c programming and there are various methods that I cannot choose from. I believe with new features I can do it much more simple in swift. So my question is how should I create C library and use it in iOS project? Can I use cmake? Should I use Swift package manager like what said in first link below?
best result I found on internet:
This is the only go-to graphical interface you'll use to write iOS apps. It houses everything you'll need to write code for iOS. Included with XCode is support for Apple's newer Swift programming language, made specifically for iOS and macOS. While Apple is pushing Swift, you can also program iOS in Objective-C.
Open Xcode application and select File > New > Swift Package... option or use ⌃⇧⌘ N keyboard shortcut. Alternatively, go to File > New > Project... and choose Swift Package template under Multiplatform option. Type your package name, choose your location, and hit the Create button.
Creating Libraries :: Static Library Setup First thing you must do is create your C source files containing any functions that will be used. Your library can contain multiple object files. After creating the C source files, compile the files into object files. This will create a static library called libname.
Xcode can compile a C code without additional settings. Just add your C files to project and select proper target.
To use C code at Swift you should create bridging header.
Here is an example how to use C and Swift in same project from a scratch. You can do the same with your exist C code.
Add some function at C file. For example:
// example.h
#include <stdio.h>
int exampleMax(int num1, int num2);
// example.c
#include "example.h"
int exampleMax(int num1, int num2)
{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Add C header to bridging file:
// ModuleName-Bridging-Header.h
#import "example.h"
Now you can use C code at Swift files:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let number1 = Int32(1)
let number2 = Int32(5)
let result = exampleMax(number1, number2)
print("min = \(result)")
}
}
Auto completion should see your C header:
Instead of bridging header you can use modulemap file. It's more flexible and convenient but a little harder to setup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With