CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
指定cmake最低版本
project(projectname VERSION 0.0.1 LANGUAGES CXX)
message("project_version: ${CMAKE_PROJECT_VERSION}")
message("project_version_major: ${PROJECT_VERSION_MAJOR}")
message("project_version_minor: ${PROJECT_VERSION_MINOR}")
message("project_version_path: ${PROJECT_VERSION_PATCH}")
project()里面指定了工程名,程序版本号和程序使用的语言
if(CMAKE_VERSION VERSION_LESS "3.7.0")
set(CMAKE_INCLUDE_CURRENT_DIR ON)
endif()
set(CMAKE_AUTOUIC ON)
使用Qt的uic.exe 把.ui文件转化为 ui_文件名.h文件
set(CMAKE_AUTOMOC ON)
使用Qt的moc.exe 把qt扩展的c++语法编译成标准c++代码(如: Q_OBJECT)
set(CMAKE_AUTORCC ON)
使用Qt的rcc.exe 把.qrc文件转为 qrc_文件名.cpp文件
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
指定C++版本,Qt6的至少需要 C++ 17版本
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
(兼容Qt5和6的CMake编译),给${QT_VERSION_MAJOR}
赋值
如果明确Qt使用版本可以简单的编写 find_package(Qt5 REQUIRED COMPONENTS Widgets)
set(PROJECT_SOURCES
main.cpp
MainWindow.cpp
MainWindow.h
MainWindow.ui
)
将需要进行编译的文件名字赋值给${PROJECT_SOURCES}
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
qt_add_executable(${PROJECT_NAME}
MANUAL_FINALIZATION
${PROJECT_SOURCES}
)
else()
add_executable(${PROJECT_NAME} ${PROJECT_SOURCES})
endif()
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE Qt${QT_VERSION_MAJOR}::Widgets)
引用Qt5Widgets.lib, 如果需要引用其他lib,如Websocket,
find_package(Qt5 REQUIRED COMPONENTS Widgets Websockets)
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE Qt5::Widgets Qt5::Websockets)
第一个字母大写,兼容(Qt5,6写法) Qt${QT_VERSION_MAJOR}::Websockets
set_target_properties(${CMAKE_PROJECT_NAME} PROPERTIES
WIN32_EXECUTABLE TRUE
)
install(TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
设置库的安装路径,具体请看CMake文档
安装命令: cmake --install <dir>
if(QT_VERSION_MAJOR EQUAL 6)
qt_finalize_executable(untitled29)
endif()
注意
${PROJECT_NAME}
和${CMAKE_PROJECT_NAME}
都是表示工程名称,会有点区别