Issue description:
- I’m new to Xcode and I’m making a “Hello world” in C++.
- I created an empty “static library” project in Xcode and added
main.cpp
,main.h
andBridging-Header.h
. - I created an empty “app” project to display the text output of the above static library (in the iOS simulator) and I included it as the only dependency.
- Calling
testC()
produces text output in the app, so everything works up to this point. - But calling
testCpp()
fails atstd::string
part. - It seems that
std
(C++ standard library) is not accessible in the “static library” project. Does anyone know how to fix it?
What I tried:
- I produced a separate CommandLine project and the same
testCpp()
works in that project. - I tried modifying “Build Settings” to include standard library (via
-stdlib=libc++
and-std=c++17
) in “Other linker flags” and in “Other C++ flags” but that didn’t help.
Xcode: 15.4
macOS: 14.6.1
MyStaticLib/main.h:
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
const char* testC();
const char* testCpp();
#ifdef __cplusplus
}
#endif
MyStaticLib/main.cpp:
#include "main.h"
#include <iostream>
#include <string>
// This function fully works.
const char* testC() {
return "testC(): Hello from C!";
}
// This doesn't work.
const char* testCpp() {
static const std::string message = "testCpp(): Hello from C++!";
return message.c_str();
}
MyStaticLib/Bridging-Header.h:
#include "main.h"
MyStaticLib/MyClass.swift:
public class MyClass {
public init() {}
public func ExampleMethod() {
print("Static library works.");
let message = String(cString: testCpp()); // This fails.
print(message);
}
}
TestApp/TestAppMain.swift:
import Foundation
import SwiftUI
import MyStaticLib
@main
struct TestAppMain: App {
var body: some Scene {
WindowGroup {
ContentView()
.onAppear(perform: customFunction)
}
}
func customFunction() {
let instance = MyStaticLib.MyClass();
instance.ExampleMethod();
}
}
The error is this:
Undefined symbol: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>::__init(char const*, unsigned long)
Undefined symbol: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>::~basic_string()
Undefined symbol: std::terminate()
Undefined symbol: ___cxa_begin_catch
[...]
Linker command failed with exit code 1 (use -v to see invocation)
1
I solved it! It took 8 hours of trial and error and I found “C++ and Objective-C Interoperability” flag in “Build Settings”. It needs to be switched from C to C++.
I’m not sure why such flag even exists and why it wouldn’t be selected to support C++ by default and why we can choose only C or C++ but not both, but so far it works.
1