“undefined reference to `vtable for …’ errors” in Qt derived classes April 24, 2009
Posted by lizardo in Hints.Tags: qt
trackback
If you ever come across an error like this when compiling C++ code with Qt derived class definitions:
g++ -Wl,--no-undefined -o test test.o -L/usr/lib -lQtGui -lQtCore -lpthread
test.o: In function `main':
test.cpp:(.text+0x2c): undefined reference to `vtable for MyClass'
collect2: ld returned 1 exit status
make: *** [test] Error 1
It is probably because either you defined a class in a .cpp file or you forgot to add some header file to the HEADERS variable in the .pro file.
This happens because moc (Qt’s meta-object compiler) only runs on header files by default (and only on those listed in the HEADERS variable), therefore it did not generate the necessary MOC code for that class.
The fix is to simply move the class definition to a header, and make sure it is added to the HEADERS variable in the qmake project file.
Comments
Sorry comments are closed for this entry
… or you can add something like this (supposing that MyClass definition is under MyClass.cpp file):
#include “MyClass.moc”
At the end of MyClass.cpp file
It is very useful when you need to define private classes (see http://techbase.kde.org/Policies/Library_Code_Policy#D-Pointers ) which doesn’t need to be visible from header files.