概述:用CMake可以方便地构建Qt的应用程序,前提是你已经配置好用Visual Stdio 开发的Qt的环境或者Xcode的Qt开发环境。
1、编写CMakeLists.txt
cmake_minimum_required(VERSION 3.6)set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "My multi config types" FORCE)set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set_property(GLOBAL PROPERTY AUTOGEN_TARGETS_FOLDER AutoMoc)set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)project(CcQtApp)if(WIN32)add_definitions("/wd4819")
elseif(APPLE) SET(CMAKE_OSX_DEPLOYMENT_TARGET "10.12")
endif(WIN32)macro(ADD_FRAMEWORK fwname appname)
find_library(FRAMEWORK_${fwname}NAMES ${fwname}PATHS ${CMAKE_OSX_SYSROOT}/System/LibraryPATH_SUFFIXES FrameworksNO_DEFAULT_PATH)
if( ${FRAMEWORK_${fwname}} STREQUAL FRAMEWORK_${fwname}-NOTFOUND)MESSAGE(ERROR ": Framework ${fwname} not found")
else()TARGET_LINK_LIBRARIES(${appname} ${FRAMEWORK_${fwname}})MESSAGE(STATUS "Framework ${fwname} found at ${FRAMEWORK_${fwname}}")
endif()
endmacro(ADD_FRAMEWORK)if(WIN32)set(QtVersion 5.14)
elseif(APPLE)set(QtVersion 5.7)
elseif(LINUX)set(QtVersion 5.14)
endif()if(WIN32)set(exe_property WIN32)set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MD /Zi /MP /Gm- /Qpar /wd4996")set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MDd")set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /DEBUG /OPT:REF /OPT:ICF /LARGEADDRESSAWARE")add_definitions(-DUNICODE -D_UNICODE -D_SCL_SECURE_NO_WARNINGS -DWIN32 -DV_LOG -DCURL_STATICLIB)elseif(APPLE)SET(BUILD_WITH_INSTALL_RPATH TRUE)set(exe_property MACOSX_BUNDLE)set (CMAKE_CXX_FLAGS "--std=gnu++11 ${CMAKE_CXX_FLAGS}")message("CMAKE_OSX_DEPLOYMENT_TARGET is ${CMAKE_OSX_DEPLOYMENT_TARGET}")
elseif(LINUX)SET(CMAKE_BUILD_TYPE Debug)SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")
endif(WIN32)# 引入Qt的核心库
find_package(Qt5Core $ENV{QTVERSION} REQUIRED)
find_package(Qt5Gui $ENV{QTVERSION} REQUIRED)
find_package(Qt5Widgets $ENV{QTVERSION} REQUIRED)set (NAME CcQtApp)add_executable(${NAME} ${exe_property} main.cpp)# 使用Qt核心库
qt5_use_modules(${NAME} Core)
qt5_use_modules(${NAME} Gui)
qt5_use_modules(${NAME} Widgets)
2、编写main.cpp测试demo
#include <QApplication>
#include <QWidget>int main(int argc, char *argv[])
{QApplication app(argc, argv);QWidget window;window.resize(650, 350);window.setWindowTitle("简单的cmake构建的Qt窗口程序");window.show();return app.exec();
}
3、创建一个build文件夹(生成项目文件,不用污染源代码,方便阅读)
4、进入build目录执行以下命令
cmake -G"Visual Studio 16 2019" -A Win32 ..
说明-A Win32生成的是win32(x86)的工程,默认不写为x64
5、在build下打开.sln文件
6、打开sln进行编译