如何解决“缺少 vtable 通常意味着第一个非内联虚拟成员函数没有定义。”

How to solve " a missing vtable usually means the first non-inline virtual member function has no definition."

我试图查看虚函数是如何编译的,但似乎我无法在 macOS 上将一个简单的示例编译为 dylib。

我经历过无数次此代码和 SO 答案的排列,但我无法通过以下方式编译这个微不足道的示例(或者更确切地说 link):

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 是一个 polymorphic class),所以这个错误实际上意味着你需要 link 反对 C++标准库。

最简单的方法是在您编写的命令行中将 clang 更改为 clang++difference between clang and clang++是前者默认编译link为C,后者默认编译linkC++,但都可以编译两种语言。