QObject, QMake and Sadness - ‘Undefined reference to vtable’

Mmmm… Bit of a longwinded title there! Basically, I could not shake off the following error recently, when writing a class Browser which inherited from QObject. Apparently, the answer is that sometimes you simply have to delete your Makefiles and regenerate them using QMake (KDevelop automatically creates Makefiles from me if none are found), in order to get over this error.

/path/to/frogface/trunk/src/browser.cpp:38:
undefined reference to `vtable for Browser’
browser.o: In function `Browser’:
/path/to/frogface/trunk/src/browser.cpp:34:
undefined reference to `vtable for Browser’
/path/to/frogface/trunk/src/browser.cpp:34:
undefined reference to `vtable for Browser’
collect2: ld returned 1 exit status
gmake[1]: *** [../bin/frogface] Error 1
gmake: *** [sub-src-make_default] Error 2
*** Exited with status: 2 ***

Thanks to the patient folks on the QT mailing for the help!

Funnily enough as I write this, someone’s just posted the following checklist on the #qt irc channel, which is good advice

  1. Make sure the Q_OBJECT macro is present in the definition of all QObject-derived classes
  2. Make sure you define your QObject-derived classes in your header files ONLY
  3. Make sure all of your header files are listed in your .pro file in the HEADERS= list
  4. Run qmake every time you add Q_OBJECT to one of your classes or modify your .pro file
  5. The last one is particularly important as I’ve made an art form out of forgetting it :)

3 Responses to “QObject, QMake and Sadness - ‘Undefined reference to vtable’”

  1. David Gillies Says:

    Thank you, thank you, thank you! I was about ready to give up in disgust when I read your line about adding HEADERS= to the .pro file. Could I find this on Trolltech’s site? I could not.

  2. Nick Toole Says:

    I had a similar issue, but am not using qmake in my build process.

    Instread, I resolved the issue by #include-ing the moc-generated file (input: Abc.h; output: moc_Abc.cpp) in the implementation file (moc_Abc.cpp). Not sure if this is obvious, but I didn’t see it in the primary Trolltech Qt tutorial example I have been reading.

    Thanks for the entry.

  3. hribek Says:

    Thank you very much you saved my day. Actually this is the answer to mine problems with compiling qt in Code::Blocks.

Leave a Reply