Add static c library to xcode/swift

Hi, I want to build an ios app that uses static c libraries. For reference, i did the following as a test:

  1. Compiled a simple c date and time program with

clang -c -arch arm64 -sysroot <iPhoneOSSDK_path> date.c -o date_arm64.o

  1. Created the static lib

ar rcs libdatetime_arm64.a date_arm64.o

  1. Added the lib in my Xcode project.
  • Added the (.a) file in Build Rules -> Link Binary With Libraries
  • Included the (.a) and (.h) file path in Build Settings -> Search Paths -> Header and Library Search Path
  1. Created a Bridging-Header.h file where I added

#import "date.h"

  1. In my App.swift file, I called the function for getting the date and time

let dateTimeStr = String(cString: get_current_datetime())

print("Current Date and Time: \(dateTimeStr)")

After doing all the steps above, I am met with the error - Cannot find 'get_current_datetime' in scope

Is there any other method to use static c libraries in xcode?

Answered by DTS Engineer in 827427022

There are lots of way you can do this. It sounds like you want to:

  • Build the static library from source code

  • And then use it from Swift

If so, the best option is to use Swift Package Manager to create a C package containing your library’s code. You’ll need to build a module map from your headers but, once you do that, you can import the library into Swift like you would any other package.

The advantage of this approach is that you can skip all the messing around with header search paths.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

There are lots of way you can do this. It sounds like you want to:

  • Build the static library from source code

  • And then use it from Swift

If so, the best option is to use Swift Package Manager to create a C package containing your library’s code. You’ll need to build a module map from your headers but, once you do that, you can import the library into Swift like you would any other package.

The advantage of this approach is that you can skip all the messing around with header search paths.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Add static c library to xcode/swift
 
 
Q