Compiling QObject-derived class on the command lin

2019-07-15 02:03发布

问题:

I am new to Qt. I am trying to compile a small code snippet shown below:

#include<QtCore/QtCore>
#include<QtCore/QObject>

class Test:public QObject
{
  Q_OBJECT
  public:
  Test(){qDebug()<<"CTOR";}
};

int main()
{
Test t;
return 0;
}

I am trying to run it through command line using the following command:

g++ -o signalTest.exe -l QtCore signalTest.cpp

However I am getting the following error:

undefined reference to vtable for Test

I think I need to include the library for QObject, but I am not really sure. Any ideas?

回答1:

You are not using the meta object compiler, aka. moc, properly.

You have a QObject in the source as opposed to the header, so instead of including the header into the HEADERS variable for qmake, you will need to include the generated moc file in your source code as demonstrated below.

Please note that you should add the Q_OBJECT macro to your Q_OBJECT in general due to the propeties, signals, and slots that it makes available. This is not strictly necessary to fix this issue, but it is better if you are aware of this.

main.cpp

#include<QtCore/QtCore>
#include<QtCore/QObject>

class Test:public QObject
{
  Q_OBJECT
  public:
  Test(){qDebug()<<"CTOR";}
};

#include "main.moc" // <----- This will make it work

int main()
{
Test t;
return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make