带有 CMake 的 Qt 应用程序中的静态链接库

KMK*_*KMK 5 linux qt cmake static-linking qt5

我正在尝试使用 CMake 使用静态库构建 Qt5 应用程序,但我不知道如何静态链接文件。我已经坚持了几个小时并试图在谷歌上找到任何线索,但没有运气。

CMakeLists.txt:

cmake_minimum_required(VERSION 3.9 FATAL_ERROR)   

project (myDemo VERSION 0.1 LANGUAGES CXX)

### Didn't make any difference:
###set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
   
set (myDemo_VERSION_MAJOR 1)    
set (myDemo_VERSION_MINOR 0)

set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin)    
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})    
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(CMAKE_INSTALL_PREFIX ${PROJECT_BINARY_DIR}/installation)

set(CMAKE_AUTOMOC ON)

set(SOURCES ${PROJECT_SOURCE_DIR}/src)

#### This made the build process reach 100%, but still exiting with the same error message
###set(Qt5_USE_STATIC_LIBS ON)    
###set(Qt5_USE_STATIC_RUNTIME ON)

# Find the necessary qt libraries    
find_package(Qt5 COMPONENTS Gui Quick Qml Multimedia)

if ( NOT Qt5_FOUND )    
 message(FATAL_ERROR "Package QT not found!")    
endif( )

# add the executable    
add_executable(myDemo src/main.cpp     
    src/somefile.cpp     
    src/somefile.h )

target_include_directories(myDemo PRIVATE Qt5_DIR)    
target_compile_features(myDemo PUBLIC cxx_std_17)     

target_link_libraries (myDemo Qt5::Gui Qt5::Qml Qt5::Quick Qt5::Multimedia ${ADDITIONAL_LIBRARIES} -static)      

install (TARGETS myDemo DESTINATION bin)
Run Code Online (Sandbox Code Playgroud)

cmake命令退出没有错误,但make具有以下错误消息的命令退出:

/usr/bin/ld:尝试动态对象`/opt/qt5/lib/libQt5Quick.so.5.9.1'的静态链接

collect2: 错误: ld 返回 1 个退出状态

CMakeFiles/myDemo.dir/build.make:204:目标“../bin/myDemo”的配方失败

make[2]: *** [../bin/myDemo] 错误 1

CMakeFiles/Makefile2:67:目标“CMakeFiles/myDemo.dir/all”的配方失败

make[1]: *** [CMakeFiles/myDemo.dir/all] 错误 2

Makefile:129: 目标“all”的配方失败

make: *** [all] 错误 2

我在美德机器上运行 Ubuntu,应用程序是用 QML/Qt (5.9) 实现的。我正在使用 Virtual Studio Code(而不是 Qt Creator)。

我之前没有使用 CMake 的经验。

有没有人知道如何链接静态 Qt 库?

编辑

问题可能是我有 Qt 的开源版本。是否可以解释开源版本不支持静态构建?

She*_* O. -1

如果你在Windows下工作,我建议使用MSYS2,然后使用pacman静态安装qt并安装cmake和gcc(如果你想使用pro文件),这样会减少以后的工作量。然后在 Qt Creator 中调整套件编译器以使用您刚刚安装的 msys2 中的静态编译器,因为用于您的应用程序和库的编译器必须相同。这些命令是针对编译器的,我不记得安装qt的命令了。

 pacman -S mingw-w64-x86_64-gcc

 gcc -v #to make sure gcc is installed

 g++ -v # check g++ compiler

 pacman -S make

 pacman --needed -S mingw-w64-x86_64-toolchain
Run Code Online (Sandbox Code Playgroud)

如果您在 Mac 上工作,该过程将是相同的,但使用brew,您的 cmake 文件中会有一个例外添加此

set(CMAKE_EXE_LINKER_FLAGS "-lobjc -framework IOKit -framework CoreFoundation")
Run Code Online (Sandbox Code Playgroud)