如何在MSYS2中使用CMake构建C++ Qt5应用程序

3

我有一个c++ qt5的"hello world" cmake项目; 这里分别是我的main.cpp和CMakeLists.txt文件:

#include <QApplication>
#include <QWidget>
#include <QGridLayout>
#include <QLabel>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QWidget widget;
    widget.resize(640, 480);
    widget.setWindowTitle("Hello, world!!!");

    QGridLayout *gridLayout = new QGridLayout(&widget);

    QLabel * label = new QLabel("Hello, world!!!");
    label->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter);
    gridLayout->addWidget(label);

    widget.show();

    return app.exec();
}

cmake_minimum_required(VERSION 3.1.0)

project(helloworld)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

if(CMAKE_VERSION VERSION_LESS "3.7.0")
    set(CMAKE_INCLUDE_CURRENT_DIR ON)
endif()

message("cmake source dir = ${CMAKE_SOURCE_DIR}")

set (Qt5_DIR "/mingw64/lib/cmake/Qt5")

find_package(Qt5 COMPONENTS Widgets REQUIRED)

add_executable(helloworld
    main.cpp
)

target_link_libraries(helloworld Qt5::Widgets)

我只是从官方网页复制了CMakeList,并编写了一些非常基本的main.cpp。然后我在我的Linux(openSUSE 15.0)上构建它,一切都很正常。现在我想在MSYS2上构建(以获得Windows版本)。起初,我无法构建cmake项目,因为找不到Qt5Config.cmake文件。我添加了

set (Qt5_DIR "/mingw64/lib/cmake/Qt5")

手动查找Qt5Config.cmake文件。 将此添加到我的cmake文件后,该项目已成功构建。 但是当我运行make编译程序时,我会收到以下错误:

[ 25%] Automatic MOC and UIC for target helloworld
[ 25%] Built target helloworld_autogen
[ 50%] Linking CXX executable helloworld.exe
CMakeFiles/helloworld.dir/main.cpp.o:main.cpp:(.text$_ZN15QTypedArrayDataItE10deallocateEP10QArrayData[_ZN15QTypedArrayDataItE10deallocateEP10QArrayData]+0x1c): undefined reference to `QArrayData::deallocate(QArrayData*, unsigned long, unsigned long)'
CMakeFiles/helloworld.dir/main.cpp.o:main.cpp:(.text$_ZN15QTypedArrayDataItE10deallocateEP10QArrayData[_ZN15QTypedArrayDataItE10deallocateEP10QArrayData]+0x1c): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `QArrayData::deallocate(QArrayData*, unsigned long, unsigned long)'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/helloworld.dir/build.make:102: helloworld.exe] Error 1
make[1]: *** [CMakeFiles/Makefile2:73: CMakeFiles/helloworld.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

据我了解,可能存在找不到的一些缺失库。但我不知道如何修复它。


你是如何安装Qt的? - David Grayson
@DavidGrayson,pacman -S mingw-w64-x86_64-qt5 - Marseille
1个回答

0

您不需要CMakeLists.txt文件,只需按下构建按钮即可。


你可以使用这个 https://github.com/PLLUG/CPPQT-MSYS2-Cmder。在此之后,你需要使用两个命令 install-dev-env 和 install-qt5-env,然后 qtcreator 和 Git 就会被安装好了。 - Orest
抱歉,但我没有任何构建按钮。我想使用CMake在Linux和MSYS2上以相同的方式构建我的应用程序。我只使用vim创建我的Qt5 GUI应用程序。这样做有问题吗? - Marseille
你必须使用Qt Creator。 - Orest

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接