简体   繁体   中英

Compiling QObject-derived class on the command line on Linux

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM