CMake和QT不会链接到QT库

时间:2018-10-10 22:28:00

标签: qt cmake

我刚开始使用cmake和QT。我一直在与qt designer一起工作,并且在qmake中有一个有效的项目。我想迁移到部落和cmake,过去我有些运气不好,这是我最近遇到的障碍。

我使用qt5_use_modules,也尝试过target_link_libraries,但是都没有用。编译工作正常,但链接失败,我似乎丢失了什么?

CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)
project(HelloQT)

set(CMAKE_CXX_STANDARD 14)
# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Instruct CMake to run moc automatically when needed
set(CMAKE_AUTOMOC ON)
# Create code from a list of Qt designer ui files
set(CMAKE_AUTOUIC ON)

list(APPEND CMAKE_PREFIX_PATH C:\\Qt\\5.8\\mingw53_32\\lib\\cmake)
find_package(Qt5 REQUIRED Core)

add_executable(HelloQT main.cpp)
qt5_use_modules(HelloQT LINK_PUBLIC Core)
#target_link_libraries(HelloQT Qt5::Core) # using this instead of qt5_use_modules fails with the exact same message

main.cpp:

#include <iostream>
#include <QString>

int main() {
    QString hello = "Hello, QT Workld!";
    std::cout << hello.toStdString() << std::endl;
    return 0;
}

导致:

[ 25%] Automatic MOC and UIC for target HelloQT
[ 25%] Built target HelloQT_autogen
[ 50%] Linking CXX executable HelloQT.exe
CMakeFiles\HelloQT.dir/objects.a(main.cpp.obj): In function `QArrayData::data()':
C:/Qt/5.8/mingw53_32/include/QtCore/qarraydata.h:59: undefined reference to `__imp__Z9qt_assertPKcS0_i'
CMakeFiles\HelloQT.dir/objects.a(main.cpp.obj): In function `QString::toUtf8() const &':
C:/Qt/5.8/mingw53_32/include/QtCore/qstring.h:531: undefined reference to `__imp__ZN7QString13toUtf8_helperERKS_'
CMakeFiles\HelloQT.dir/objects.a(main.cpp.obj): In function `QString::QString(char const*)':
C:/Qt/5.8/mingw53_32/include/QtCore/qstring.h:674: undefined reference to `__imp__ZN7QString16fromAscii_helperEPKci'
CMakeFiles\HelloQT.dir/objects.a(main.cpp.obj): In function `QTypedArrayData<char>::deallocate(QArrayData*)':
C:/Qt/5.8/mingw53_32/include/QtCore/qarraydata.h:228: undefined reference to `__imp__ZN10QArrayData10deallocateEPS_yy'
CMakeFiles\HelloQT.dir/objects.a(main.cpp.obj): In function `QTypedArrayData<unsigned short>::deallocate(QArrayData*)':
C:/Qt/5.8/mingw53_32/include/QtCore/qarraydata.h:228: undefined reference to `__imp__ZN10QArrayData10deallocateEPS_yy'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [HelloQT.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/HelloQT.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles/HelloQT.dir/rule] Error 2
CMakeFiles\HelloQT.dir\build.make:124: recipe for target 'HelloQT.exe' failed
CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/HelloQT.dir/all' failed
CMakeFiles\Makefile2:78: recipe for target 'CMakeFiles/HelloQT.dir/rule' failed
mingw32-make.exe: *** [HelloQT] Error 2
Makefile:117: recipe for target 'HelloQT' failed

1 个答案:

答案 0 :(得分:1)

对导入的目标使用target_link_libraries而不是qt5_use_modules

target_link_libraries(HelloQT Qt5::Core)