Qt报错 error: undefined reference to `vtable for Dialog’ 问题解决

今天,我在学习Qt的时候,报了个错error: undefined reference to `vtable for Dialog’ ,我检查几遍代码,也没发现有什么问题,但就是编译报错,但通过网上搜索,我总算是找到了问题解决方法,特记录在此,以防下次遇到这个问题,忘记如何解决。

原代码:

/main.cpp

#include <QApplication>

#include "Dialog.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Dialog *dlg = new Dialog;
    dlg->show();

    return a.exec();
}
/Dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QWidget>
#include <QDialog>
#include <iostream>
#include <QObject>

class Dialog : public QDialog{

    Q_OBJECT

    public:

        Dialog(QWidget *parent = NULL);
        ~Dialog();
};

Dialog::Dialog(QWidget *parent) : QDialog(parent)
{

}

Dialog::~Dialog()
{

}

#endif // DIALOG_H
/pro file

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp

HEADERS += \


FORMS +=

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

编译后报错:

解决方案:

该问题是由于添加了Q_OBJECT宏定义导致的,出现的原因在于最终的 Makefile 里没有将 moc_xxx.cpp 加入编译引起,而这个依赖关系是由 moc 工具写入到 makefile 中的。

因此只需要用moc.exe生成xxx.moc文件然后导入即可。

成功:

标签