Compiling QObject-derived class on the command line on Linux

你。 提交于 2019-12-11 04:03:54

问题


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


来源:https://stackoverflow.com/questions/20971887/compiling-qobject-derived-class-on-the-command-line-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!