8

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
Cœur
  • 37,241
  • 25
  • 195
  • 267
zMk
  • 91
  • 1
  • 6

1 Answers1

12

Xcode can compile C code without additional settings. Just add your C files to your project and select a proper target.

One way to use C code from Swift is with a bridging header (another way is to use a modulemap file, it's more flexible and convenient but also a bit more complex to setup).

Here is an example on how to use C and Swift in the same project, you can use the same technique with your existing C code.

  1. Create a new iOS project.

  2. Add a new C file with a corresponding header (Xcode will prompt you). C file

  3. Xcode should suggest to add a bridging header and create it automatically. If it doesn't happen you can create it manually and add it to your project's Build Settings. Bridging header Build settings

  4. Add some code to your .c and .h files, 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 your C header to the bridging file:

     // ModuleName-Bridging-Header.h
     #import "example.h"
    
  6. Now you can call your C function from Swift:

     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 recognize your C interface:

Auto completion

joakie
  • 144
  • 2
  • 6
Anton Vlasov
  • 1,372
  • 1
  • 10
  • 18
  • I do not want to copy all files whenever some changes happen in c code so I prefer to use library. Isn't using library a better approach? – zMk May 14 '19 at 04:01