[英]Can't build Qt-Widgets Application using CMake
我正在尝试设置一个构建 Qt-Widgets 应用程序的 CMake 项目,但无法正确编译它。 我的项目结构如下:
cmake_minimum_required(VERSION 3.10)
find_package(Qt5 COMPONENTS Widgets REQUIRED)
project(Test VERSION 0.1 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC_SEARCH_PATHS resources)
add_executable(App src/mainwindow.cpp src/main.cpp resources/mainwindow.ui)
target_include_directories(App PRIVATE include)
target_link_libraries(App PRIVATE Qt5::Widgets)
#ifndef MAINWINDOW_HPP_
#define MAINWINDOW_HPP_
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class Test : public QMainWindow {
Q_OBJECT
public:
Test(QWidget *parent = nullptr);
~Test();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_HPP_
#include "mainwindow.hpp"
#include "ui_mainwindow.h"
Test::Test(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow){
ui->setupUi(this);
}
Test::~Test(){
delete ui;
}
#include "mainwindow.hpp"
#include <QApplication>
int main(int argc, char *argv[]){
QApplication a(argc, argv);
Test w;
w.show();
return a.exec();
}
当我尝试构建项目时:
cmake -Bbuild -DCMAKE_BUILD_TYPE=Debug
cmake --build build --target all
我收到以下链接器错误:
[ 20%] Automatic MOC and UIC for target App
[ 20%] Built target App_autogen
[ 40%] Building CXX object CMakeFiles/App.dir/App_autogen/mocs_compilation.cpp.o
[ 60%] Building CXX object CMakeFiles/App.dir/src/mainwindow.cpp.o
[ 80%] Building CXX object CMakeFiles/App.dir/src/main.cpp.o
[100%] Linking CXX executable App
/usr/bin/ld: CMakeFiles/App.dir/src/mainwindow.cpp.o: in function `Test::Test(QWidget*)': .../src/mainwindow.cpp:4: undefined reference to `vtable for Test'
/usr/bin/ld: .../src/mainwindow.cpp:4: undefined reference to `vtable for Test'
/usr/bin/ld: CMakeFiles/App.dir/src/mainwindow.cpp.o: in function `Test::~Test()': .../src/mainwindow.cpp:8: undefined reference to `vtable for Test'
/usr/bin/ld: .../src/mainwindow.cpp:8: undefined reference to `vtable for Test'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/App.dir/build.make:132: App] Error 1
make[1]: *** [CMakeFiles/Makefile2:84: CMakeFiles/App.dir/all] Error 2
make: *** [Makefile:91: all] Error 2
查看 cmakes 生成的link.txt
,似乎所需的目标文件已正确链接
/usr/bin/c++ \
-g CMakeFiles/App.dir/App_autogen/mocs_compilation.cpp.o \
CMakeFiles/App.dir/src/mainwindow.cpp.o \
CMakeFiles/App.dir/src/main.cpp.o \
-o App \
/usr/lib/libQt5Widgets.so.5.15.4 \
/usr/lib/libQt5Gui.so.5.15.4 \
/usr/lib/libQt5Core.so.5.15.4
我不太确定,为什么 vtable 引用未定义。 我在这里做错了什么?
解决方案是将include/mainwindow.hpp
添加到源中。
add_executable(App src/mainwindow.cpp src/main.cpp include/mainwindow.hpp resources/mainwindow.ui)
生成的ui_mainwindow.h
似乎需要这才能查看 MainWindow 类的 vtable 条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.