Throwing Swift, C and Obj-C into one blender using CMake on MacOS
Whenever you have a project which requires to be built on multiple systems you can either have many project files, makefiles and/or scripts which run individually across different operating systems and devices, or you have a central meta-build system like CMake. With CMake you have a global definition of partly abstract requirements which may be host and target dependent.
Like with Simple Direct media Library (SDL), having exported C symbol is very convenient, because you can bind those to different build systems and codes of different languages, even with Android and its Java Native Interface (JNI). With higher level languages (also C++) this gets much more complicated, because you have to deal with name mangling.
Being able to call C code from Obj-C or Swift is well documented here:
But how about calling Swift functions from C Code? Well, CMake provides a nice example bridging C, ObjC and Swift together. This is one way to do it, but it’s also possible to skip the ObjC part and bridge C and Swift directly.
Requirements
- Xcode installed
- CMake build system installed
Howto use SwiftMix
Even better news: The CMake source code provides many tests and one of these shows how it is done. So let’s get our hands dirty :-).
First of all get the sources:
git clone https://github.com/Kitware/CMake.git
Now create a build-directory and let cmake run over it:
mkdir build-swiftMix
cd build-swiftMix
cmake <CMake-Sources>/Tests/SwiftMix -G Xcode
Note: The generator is Xcode. Unfortunately the generators for Makefiles and Ninja do not work so well yet. CMake generates an Xcode project file which you can open with the IDE or just build the app from the terminal with:
cmake --build .
And yes, you can even debug the codes in all the three languages. If you open the project file, just ensure the right executable is selected and „Debug executable“ is checked (Edit Scheme). Now set some breakpoints and run it:
Debugging the C part:
The Obj-C part:
And the Swift part:
As you can see, the variables in the watch are correctly displayed and you also see the full call stack of your thread, all good with the Low Level Debugger (lldb).
Why would this be useful if Apple only? Well, many projects provide an extra Xcode project file, so you have a chance to deploy your app on Apple. If your main systems are Windows and Linux, Swift and Obj-C wouldn’t be the language of choice, rather something more like C or C++, maybe even Java or Kotlin. But the great thing about CMake is that you can let it detect what your host and targets are and let decide what to use. Obj-C and even Swift might be required for you, if you plan to build a cross library or application, and you require better access to the Apple APIs.
Neueste Kommentare