Wednesday, July 18, 2012

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

(From Stack Overflow)
 Answer:

Assuming those methods are in one of the libs it looks like an ordering problem.
When linking libraries into an executable they are done in the order they are declared.
Also the linker will only take the methods/functions required to resolve currently oustanding dependencies. If a subsequent library then uses methods/functions that were not originally required by the objects you will have missing dependencies.
How it works:
  • Take all the object files and combine them into an executable
  • Resolve any dependecies among object files.
  • Foreach library in order:
    • Check unresolved dependencies and see if the lib resolves them.
    • If so load required part into the executable.
Example:
Objects requires:
  • Open
  • Close
  • BatchRead
  • BatchWrite
Lib 1 provides:
  • Open
  • Close
  • read
  • write
Lib 2 provides
  • BatchRead (but uses lib1:read)
  • BatchWrite (but uses lib1:write)
If linked like this:
gcc -o plop plop.o -l1 -l2
Then the linker will fail to resolve the read and write symbols.
But if I linki the application like this:
gcc -o plop plop.o -l2 -l1
Then it will link correctly. As l2 resolves the BatchRead and BatchWrite dependencies but also adds two new ones (read and write). When we link with l1 next all four dependencies are resolved.

No comments:

Post a Comment