iOS中连接混编C++库的编译问题
问题
重新封装画板内核库后,所有的混编文件(.mm)都被打包到了库中,外面应用层代码全部都是OC
文件(.m)。这时候编译工程会出现如下连接错误:
Undefined symbols for architecture arm64:
“vtable for cxxabiv1::vmi_class_type_info”, referenced from:
…
NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
“std::1::basic_string<char, std::1::char_traits, std::1::allocator >::assign(char const*)”, referenced from: cxa_pure_virtual”, referenced from:
…
“_
…
“std::1::basic_string<char, std::1::char_traits, std::1::allocator >::operator=(std:: 1::basic_string, std::1::allocator > const&)”, referenced from: 1::vector_base_common
…
“std:::: throw_out_of_range() const”, referenced from:
…
“std::1::basic_string<char, std::1::char_traits, std::1::allocator >::basic_string(std:: 1::basic_string, std::1::allocator > const&)”, referenced from: cxa_guard_release”, referenced from:
…
“std::terminate()”, referenced from:
…
“_
…
“_cxa_guard_abort”, referenced from:
…
“std::1::basic_string, std::1::allocator >:: init(char const*, unsigned long)”, referenced from:
…
“std::1::basic_string<char, std::1::char_traits, std::1::allocator >::reserve(unsigned long)”, referenced from: gxx_personality_v0”, referenced from:
…
“_
…
…
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
探索
通过网上搜索到如下解决方案
- 将Build Settings->Apple LLVM7.1-Language中的Compile Sources As修改为According To File Tyle
- 将Build Settings->Apple LLVM7.1-Language中的Compile Sources As修改为Objective-C++
以上第二个方法对我不适用,修改为全部按Objective-C++方式编译源文件会出问题。第一个解决方案的话也有问题,由于项目中没有了混编文件(.mm),那么Xcode根本不会调用Objective-C++编译器,所以连接问题还是存在。
解决
将项目中的某个OC
文件(.m)强行改为后缀为mm,使其成为混编文件。
这种方法也适用于Swift工程,如果Swift
也要引用C++的混编库,那么可以增加一个空的混编文件(.mm),该文件不用实现,只是为了欺骗IDE,调出相应编译器完成连接。