【问题标题】:qt5 undefined reference to 'QApplication::QApplication(int&, char**, int)'qt5 未定义对 'QApplication::QApplication(int&, char**, int)' 的引用
【发布时间】:2025-12-24 21:15:11
【问题描述】:

我正在尝试运行一个简单的 hello world 示例,并且已经需要一些时间来弄清楚要使用的内容 现在我验证了包含路径,QApplication 实际上应该在那里,但它会引发上述错误。为了清楚起见,我的代码:

#include <QtWidgets/QApplication>
#include <QtWidgets/QPushButton>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QPushButton *button = new QPushButton("Hello world!");
    button->show();
    return app.exec();
}

我尝试先使用qmake -project进行编译,然后使用qmake,最后使用ma​​ke,然后出现以下错误:

qt_hello_world.o: In function 'main':  
undefined reference to QApplication::QApplication(int&, char**, int)  
qt_hello_world.cpp: undefined reference to QPushButton::QPushButton(QString const&, QWidget*)
qt_hello_world.cpp: undefined reference to QWidget::show()  
qt_hello_world.cpp: undefined reference to QApplication::exec()  
qt_hello_world.cpp: undefined reference to QApplication::~QApplication()
qt_hello_world.cpp: undefined reference to QApplication::~QApplication()

由 qmake 创建的 Makefile 包含到包含 QtWidgets/QApplication 的 qt5 目录的正确包含路径,QApplication 文件只包含包含实际类 QApplication 的 qapplication.h 头文件。

【问题讨论】:

  • Undefined reference to ... 是链接器错误,因此它与包含或包含目录无关
  • 但是我可以从哪里着手解决这个错误呢? Makefile 将其包含为 /usr/include/x86_64-linux-gnu/qt5,在 cpp 文件中,我将标题包含为 QtWidgets/QApplication,QApplication 文件的完整路径是 /usr/include/x86_64-linux-gnu/ qt5/QtWidgets/QApplication,不应该真的适合吗?还是我误会了什么?
  • 正如我已经提到的:因为它是链接器错误,它是 unrealted 包含。在提出这个问题之前,您在研究期间是否阅读过此内容:*.com/questions/12573816/…
  • 好像和头文件不在同一个文件夹里应该不是。话虽如此,由于您使用的是 qmake,因此您的 .pro 文件中可能存在错误。
  • 嗨 Marco(或未来的 googler),QApplication 是在 QtWidgets 库中定义的,而不是 QtCore 或 QtGUI。您需要将 QT += 小部件添加到您的 .pro 文件中。

标签: c++ qt qt5 linker-errors qapplication


【解决方案1】:

教程https://wiki.qt.io/Qt_for_Beginners 已全面更新,因此您必须对其进行修改。改为:

TEMPLATE = app
TARGET = callboot-ui.exe
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
HEADERS +=
SOURCES += main.cpp

TL;博士;

@jww 的情况下,.pro 的以下行中有错误:

greaterThan(QT_MAJOR_VERSION, 5): QT += core gui widgets

错误是因为greaterThan(QT_MAJOR_VERSION, 5)验证Qt主版本大于5添加子模块,但是Qt最新版本是5.13.2不大于5 ,所以它没有链接导致显示错误的模块。

在教程中,greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 用于支持 .pro,以便可以为 Qt4 和 Qt5 编译它,因为在 Qt4 和 Qt5 中,小部件移动到了一个称为小部件的新子模块。

【讨论】: