Hi --
I am attempting to use C++ and Swift in a single project but I am struggling with finding the proper way to do this. Ideally I want to have both my C++ and Swift code in the same project and not use a framework to keep them separate.
As an example, how would I create an object of the following C++ class:
class Foo {
public:
Foo() {
// do stuff
}
}
From what I read, it should be as simple as this:
let foo = Foo()
But Xcode says it Cannot find 'Foo' in scope. How do I import Foo into my Swift code? Is there a project setting that needs to be changed to automatically make my C++ classes available? Or do I need to create a Clang module (as described in this page: https://www.swift.org/documentation/cxx-interop/#importing-c-into-swift) to expose the C++ code to Swift? If so, where in my Xcode project should that go?
I am using Xcode 15.2 on macOS 14.2.1. I have also set the C++ and Objective-C Interoperability setting for my project to C++/Objective-C++.
do I need to create a Clang module … to expose the C++ code to Swift?
No. While it’s likely that you will want to do that once you get deep into this, it’s possible to use C++ interoperability with a bridging header. Try this:
-
Using Xcode 15.2, create a new test project from the macOS > Command Line Tool template.
-
Set the C++ and Objective-C Interoperability build setting to C++ and Objective-C interoperability (
objcxx
). -
Choose New > File and add a C++ file to your project. I called it
Waffle
. -
Xcode will ask you whether you want to create a bridging header. Agree to that.
-
Add this to that bridging header:
#include "Waffle.hpp"
-
Edit
Waffle.hpp
to look like this:#ifndef Waffle_hpp #define Waffle_hpp class Waffle { public: Waffle() { } void varnish(); }; #endif
-
And
Waffle.cpp
to look like this:#include "Waffle.hpp" #include <iostream> void Waffle::varnish() { std::cout << "Hello Cruel World!\n"; }
-
Finally, edit
main.swift
to look like this:import Foundation func main() { var w = Waffle() w.varnish() } main()
-
Choose Product > Run. The program prints:
Hello Cruel World!
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"