2015-07-24

undefined reference to `vtable for C'

This post intends to be a quick help for anyone who struggles with this error. This error came to me when I tried to compile a larger source code which was already compiling on Windows. It took me more than an hour to figure it out. Here is what I've found, from solution to details.

Possible reasons

  • C.cpp was not compiled.
  • C.o was not added to inputs.
  • There is a virtual method in the C class that is not defined (body of method not present).

Minimalistic reproduction

vtrep.cpp

class C
{
public:
  virtual ~C()
  { }
public:
  virtual int id();
};

int main()
{
  C c;
  return 0;
}

Compilation

$ g++ -c vtrep.cpp -o vtrep.o
$ g++ -o vtrep vtrep.o
vtrep.o: In function `C::~C()':
vtrep.cpp:(.text._ZN1CD2Ev[_ZN1CD5Ev]+0x13): undefined reference to `vtable for C'
vtrep.o: In function `C::C()':
vtrep.cpp:(.text._ZN1CC2Ev[_ZN1CC5Ev]+0xf): undefined reference to `vtable for C'
collect2: error: ld returned 1 exit status

Note that the error messages tell nothing about the id() method.