I'm developing a simple Qt 4 app and making my own dialog. I subclassed QDialog
, inserted the Q_OBJECT
macro in the class declaration block, and... I get
[Linker error] undefined reference to `vtable for MyDialog' and there is no moc_MyDialog.cpp generated by the moc compiler.
I am using Qt 4.1.3 on Windows XP and mingw. I followed the build process from the Qt-supplied build shell. I used qmake to create make files and compiled everything with a make command.
I have other classes that subclass QPushButton
and QObject
respectively, but they compile OK. I can't find any differences between them and the broken one.
There must be missing something in the broken class, but I'm unable to spot it.
The Meta-Object Compiler, moc , is the program that handles Qt's C++ extensions. The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes.
It's true that all C++ programs need a main function, but consider the following program. It defines a new type of variable whose constructor prints something out. An object of this type is created outside of an empty main function.
qmake got support for CONFIG += c++14 with Qt 5.4, so you can use that for projects where you are comfortable with requiring at least that version of Qt. Be sure to either use the explicit compiler flags, or use the CONFIG option, but not both at the same time, to avoid conflicting switches.
The undefined reference to "vtable for MyDialog" is caused because there is no moc file. Most c++ compilers create the vtable definition in the object file containing the first virtual function. When subclassing a qt object and using the Q_OBJECT macro, this will be in the moc*.cpp file. Therefore, this error means that the moc file is missing.
The possible problems I can think of are:
The header file for the class MyDialog.h is not added to HEADERS in the qmake file.
You ran qmake to generate the make file before adding the Q_OBJECT macro. This created a make file without the moc rules. This is easily fixed by simply running qmake again.
Your dialog derives from more than one class and QDialog is not the first class that it derives from. For qmake to work correctly, the QObject derived base class needs to be the first class that is inherited from.
If you are using Qt Creator, you might get this error if your previous deployment was failed due to some reason (like application already running). In that case, simply do a 'Clean Project' and then 'Rebuild Project' and then 'Run' to deploy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With