用Swift项目中的C ++静态库包括编译错误

我创build了一个包含以下C ++文件的静态库:

//TestClass.h File: #ifndef TESTCLASS_H_ #define TESTCLASS_H_ using namespace std; #include <string> class TestClass { public: TestClass(); virtual ~TestClass(); int sum(int x, int y) const; string chain(const string& x, const string& y) const; }; #endif /* TESTCLASS_H_ */ //TestClass.cpp File: #include<iostream> #include "TestClass.h" TestClass::TestClass() { } TestClass::~TestClass() { } int TestClass::sum(int x, int y) const { return x+y; } //Test.cpp File: string TestClass::chain(const string& x, const string& y) const { return x+y; } int main(int argc, char* argv[]) { TestClass test; cout << "1+1 = " << test.sum(1,1) << endl; cout << "Dog+Cat = " << test.chain("Dog","Cat") << endl; return 0; } 

我补充说

 -x objective-c++ 

标志在“编译源”中

 -lstdc++ 

“Info.plist其他预处理器标志”中的标志。

当我链接刚创build的静态库(使用Objective C包装文件)时,我收到4个跟随错误,我不知道如何解决它:

 Undefined symbols for architecture arm64: "vtable for __cxxabiv1::__class_type_info", referenced from: typeinfo for TestClass in libPredictionComplete.a(TestClass.o) NOTE: a missing vtable usually means the first non-inline virtual member function has no definition. "operator delete(void*)", referenced from: TestClass::~TestClass() in libPredictionComplete.a(TestClass.o) "___gxx_personality_v0", referenced from: -[CppObject init] in libPredictionComplete.a(CppObject.o) -[PredictionComplete init] in libPredictionComplete.a(PredictionComplete.o) -[PredictionComplete chain::] in libPredictionComplete.a(PredictionComplete.o) ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) 

我会欣赏任何想法。

根据我的经验,当顶级项目中没有C ++源代码时,Xcode将无法链接到C ++库。 在纯粹的Obj-C项目中也是如此,在这种情况下,你要链接到具有C ++代码的静态库。

一个较less侵入性的解决scheme是简单地在项目中包含一个空的C ++源文件(这里是一个示例cpp存根 ),它被“编译”到最终的.app二进制文件中。 它实际上不会发出任何代码,但是它使得Xcode意识到存在C ++代码,导致C ++库被链接。

这个解决scheme的好处是避免了修改Xcode中的项目设置,所以不需要添加特殊的链接器标志来强制Xcode做正确的事情。

这些是用于链接标准库的C ++设置

你应该有-x c ++而不是objective-c ++。 但是,如果您命名C ++ sorce * .cpp,则不需要指定此标志。

当我在Swift Project本身中将“-lstdc ++”编译标志添加到“其他链接器标志”部分,而不仅仅是在使用c ++文件的静态库项目中时,我将其修复了。

-lstdc++应该在“Other Linker Flags”(或OTHER_LDFLAGS )中。 请注意,只有当“C ++标准库”设置为libstdc++才能使用。

另外值得注意的是,如果目标包含任何C ++源代码,那么Xcode通常具有足够的智能以包含标准的C ++库,因此您不需要显式链接到libstdc++libc++