我试图了解虚拟函数是如何编译的,但似乎我无法在macOS上将一个微不足道的示例编译为dylib。
我已经经历了无数次这段代码和SO答案的排列,但我无法用编译(或者更确切地说是链接(这个琐碎的例子
clang -dynamiclib -o test.dylib test.cc
这是代码:
class Animal {
public:
virtual void who(){};
};
class Cat : Animal
{
public:
virtual void who();
};
void Cat::who() {
}
这是一个完整的错误:
clang -dynamiclib -o test.dylib test.cc
Undefined symbols for architecture x86_64:
"vtable for __cxxabiv1::__class_type_info", referenced from:
typeinfo for Animal in test-be905f.o
NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
"vtable for __cxxabiv1::__vmi_class_type_info", referenced from:
typeinfo for Cat in test-be905f.o
NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
恐怕NOTE
是在转移注意力。vtable for __cxxabiv1::__class_type_info
是C++标准库中的一个符号,而不是代码中的符号(std::type_info
是一个多态类(,所以这个错误实际上意味着你需要链接到C++标准库。
最简单的方法是在您编写的命令行中将clang
更改为clang++
。clang
和clang++
的区别在于,前者默认编译和链接为C,而后者默认编译和连接C++,但它们都能够编译这两种语言。