swift,  ios,  xcode

Framework with C code

How to create a framework that uses C with Xcode

Step 1:  Create a Cocoa Touch Framework

File -> New -> Project -> Cocoa Touch Framework

1
Name it SwiftCFramework

Step 2: Create xcconfig file:

2
Xcode build configuration files, more commonly known by their [xcconfig](https://nshipster.com/xcconfig/) file extension, allow build settings for your app to be declared and managed without Xcode.

Setp 3: Add xcconfig to the Configurations section of the Project Info

3
Step 4: Add swiftcframework.mapmodule and public.mapmodule files to the project

4

5
Step 5: Add C header files and make sure their Target Membership is set to Private

6
Step 6: Add a run script to remove private headers and create a public modulemap file

Name the script “Make C Header Files Private”

7

# Delete PrivateHeaders folder
rm -rf ${TARGET_BUILD_DIR}/${PRODUCT_NAME}${WRAPPER_SUFFIX}/PrivateHeaders

# Remove module.modulemap file
rm ${TARGET_BUILD_DIR}/${PRODUCT_NAME}${WRAPPER_SUFFIX}/Modules/module.modulemap

# Copy public.modulemap file and rename it to module.modulemap
cp ${SRCROOT}/Supporting/public.modulemap ${TARGET_BUILD_DIR}/${PRODUCT_NAME}${WRAPPER_SUFFIX}/Modules/module.modulemap

# Append the Swift module so you can access you Swift code in Objective-C via @import MyFramework.Swift
echo "module ${PRODUCT_NAME}.Swift { header \"${PRODUCT_NAME}-Swift.h\" }" >> ${TARGET_BUILD_DIR}/${PRODUCT_NAME}${WRAPPER_SUFFIX}/Modules/module.modulemap

Step 7: Add the framework to a test application

8
The code is available here.

Framework with C code

Subscribe to The infinite monkey theorem

Get the latest posts delivered right to your inbox