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:

  1. https://medium.com/shopify-mobile/wrapping-a-c-library-in-swift-part-1-6dd240070cef
  2. Compiling external C++ library for use with iOS project

1 Answers

3
Anton Vlasov On

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.

  1. Create a new iOS project.
  2. Add a C file by click command+N. Select C file with header. C file
  3. Xcode should suggest to add bridging header and create it automatically. If it doesn't happen you can do it manually by create header file and add it name to build settings of the project. Bridging header Build settings
  4. 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; 
     }
    
  5. Add C header to bridging file:

     // ModuleName-Bridging-Header.h
     #import "example.h"
    
  6. 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:

Auto completion

Instead of bridging header you can use modulemap file. It's more flexible and convenient but a little harder to setup.