[Solved] Undefined reference to vtable - class in main.cpp
-
In the following code I have a class derived from QMainWindow in the file 'main.cpp'. I know this is not the standard way of writing. This code give an error when compiled - 'undefined reference to vtable for TopLevelWindow' . This can be avoided if I put TopLevelWindow in a headerfile. Could somebody explain why this happens?
@
//main.cpp
#include <QtGui/QApplication>
#include <QMainWindow>class TopLevelWindow:public QMainWindow{
Q_OBJECT
public:
TopLevelWindow( QWidget *parent = 0){}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TopLevelWindow tWin;
tWin.show();
return a.exec();
}@There are posts that talk about this error, but not in this context.
Thank you!
-
Add following line before or after you main(){}
@
#include "main.moc"
@ -
We all know that subclass of QObject with Q_OBJECT must be moced.
@
moc xxx.h -o moc_xxx.cpp
@or
@
moc xxx.cpp -o xxx.moc
@And we know that, generated file contains implemention of the class. So it must be compiled and linked.
It's easy to understand, when we compile the gererated file, we should include definition of the class. But...
Now, what's the difference between moc_xxx.cpp and xxx.moc ?
moc_xxx.cpp is easy to be compiled. you can found #include "xxxx.h" in this file. So it is a compile unit.
@
cl /c moc_xxx.cpp
@
or
@
g++ -c moc_xxx.cpp
@but for xxx.moc, you can not do such thing.
- When you compile it, class definition must be found, but you can not #include"xxx.cpp" in this file.
so
@
g++ -c xxx.moc
@
can not pass.It must be included in your xxx.cpp, then
@
g++ -c xxx.cpp
@