Linking the C/C++ code with Swift

Picture 1 — the programming languages logotypes.

From my first impression, I saw how Swift is similar to C/C++ which I used before during my occupation in Embedded Software Engineering. Therefore, imminently, I came up with the invigorating idea of aggregating my Sandboxes where I tested my code.

Additionally, I had already learned that Swift supports Objective-C code via the bridging header by default when I built iOS tutorial projects. Then, I discovered that the C++ code could be linked as the C code via the “extern “C” keyword. So, let us look at what it takes to compile the program written in Swift and C++.

Firstly, you need to put your C++ files into a separate folder where you have to store your public functions from the library. Here is the project’s structure.

Sources                  
SwiftCPP LibraryCPP
main.swift include
sandbox.hpp
sandbox.cpp

For reference:

The “Sources” folder includes two folder named SwiftCPP and LibraryCPP.

Beneath “SwiftCPP” there is the main.swift file where you can call the public C functions from your library.

The “LibraryCPP” folder is located at the same level as SwiftCPP and it contains the include directory where the “sandbox.hpp” public header is stored.

The “sandbox.cpp” source file is placed on the similar level as the include folder below LibraryCPP

Secondly, add to your header file the extern “C” and conditional compilation instructions with functions’ signatures like this below.

//This is the sandbox.hpp

Thirdly, do not forget to create the body of the functions that you are going to use in your project. Here is an example of a simple function.

//This is the sandbox.cpp

Furthermore, to use your C++ code, you have to define your library in the Packages.swift

Finally, you can now import your C++ library and call the public functions which you have already defined in the “sandbox.hpp” header.

import LibraryCPP

print("The C++ function exit status is = \( sandbox())");

Here is the quick recapitulation of how to bind the C++ code with Swift:

  • Firstly, create a specific folder for the source files.
  • Secondly, paste your header into the include folder
  • Next, define your library in Swift’s package linker.
  • Don’t forget to import your library in the swift executable’s source.
  • Ultimately, you can call your public methods from the swift’s source files.

Happy coding!

Embedded iOS Developer. Je suis pour l’égalité.🇨🇭https://github.com/alimovlex