CMake工程指南(一)

📅 2026/7/12 6:50:40 👁️ 阅读次数 📝 编程学习
CMake工程指南(一)

目录

一、前言

1.1 场景:我们要编译我们的⼯程

1.2 ⽩话CMake-真实世界⾥的例⼦

二、CMake 快速开始

2.1 CMake 安装

2.2 VS Code CMake 插件安装

2.3 快速样例 - hello world ⼯程

三、CMake 命令⾏⼯具介绍

3.1 CMake ⼯程构建流程图

3.2 ⽣成构建系统

3.3 编译链接

3.4 测试

3.5 安装

2.6 打包

3.7 脚本模式

2.8 调用外部命令

2.9 查看帮助


一、前言

1.1场景:我们要编译我们的⼯程

1.2⽩话CMake-真实世界⾥的例⼦

CMake 还有哪些优势
优势
传统⽅式
CMake⽅式
改进效果
解决跨平台构建难
⼈⼯编辑Makefile等配置
⽂件
CMake⾃动帮我们⽣成构建配
置⽂件
⼀处配置,到处构建
语法简单易上⼿
Makefile 等语法复杂
语法简单,表达能⼒强⼤
⼤幅减少学习成本,提升
研发效率
解决包管理难题
⼿动查找包
⾃动查找包
包管理规规范化
IDE对CMake⽀持
度⾼
每个IDE都有⾃⼰的构建
⽅式
各个IDE都⽀持使⽤cmake来构
建程序
⼀处配置,多IDE⽀持。
结论:
CMake 语法简单易上⼿,功能强⼤,使⽤⼴泛,IDE⽀持度⾼,已经是C/C++事实上的构建标准,也是⼀个⼗分重要的C/C++⼯程管理⼯具。
学好CMake,不但使你的C/C++⼯程优雅⾼效,也能提升你的个⼈竞争⼒。

二、CMake 快速开始

2.1CMake 安装

所有cmake命令执⾏环境为:
编辑环境:VS Code
编译环境:VS Code Remote SSH模式 + Ubuntu 24.04
CMake 官⽅源代码下载地址:Download CMake
CMake 官⽅英⽂ 档地址:CMake Reference Documentation — CMake 4.4.0 Documentation
Step 1:使⽤ubuntu⾃带apt 安装:
sudo apt install cmake
Step 2:验证安装:
安装完成后,可通过以下命令验证 CMake 是否安装成功以及查看其版本。
cmake --version
cmake version 3.28.3
CMake suite maintained and supported by Kitware (kitware.com/cmake).

不同的Linux发行版可能有些不支持。我这里最低版本要求是3.18。

2.2VS Code CMake 插件安装

VS Code CMake 插件 官⽅⽂档:Get started with CMake Tools on Linux
VS Code CMake 插件有以下2点好处:
语法⾼亮和代码补全:对 CMakeLists.txt⽂件提供语法⾼亮显⽰,使代码结构更加清晰易
读。同时,⽀持代码补全功能,当你输⼊ CMake 命令或变量时,插件会⾃动提⽰可能的选项,减
少⼿动输⼊的错误和时间。
智能分析和错误检查:能够对 CMakeLists.txt⽂件进⾏智能分析,检查其中的语法错误和潜
在问题,并在编辑器中实时显⽰错误提⽰和警告信息,帮助你及时发现和解决问题。

步骤如下:

Step 0:打开 VS Code,点击左侧活动栏中的 扩展图标(或按Ctrl+Shift+X)。
Step 1:在搜索框中输⼊CMake,我们选择安装以下4个插件:
CMake
CMake Tools
CMake Language Support
CMake IntelliSence

2.3快速样例 - hello world ⼯程

本节我们将使⽤⼀个例⼦来演⽰下使⽤CMake 构建⼀个最简单的C++ 程序,⼤致了解下CMake的
使⽤⽅式。
我们创建⼀个新的hello_world⼯程。
下图展⽰了使⽤CMake 来管理hello world 程序⽣成的过程

Step 0:⽬录结构
tree hello_world
├──CMakeLists.txt
└──main.cpp
Step 1:新建⽂件-main.cpp
#include<iostream>
intmain()
{
std::cout <<"hello world!"<< std::endl;
return0;
}
Step 2:新建⽂件-CMakeLists.txt
# 1设置能运⾏此⼯程的cmake的最低版本
cmake_minimum_required(VERSION 3.18)
# 2设置项⽬名称
project(helloWorld)
# 3添加构建⽬标
add_executable(main main.cpp)
为什么需要设置最低的cmake版本?
CMake 是⼀个不断迭代的⼯具(⽬前最新4.x,历史有3.x),不同版本可能会引⼊新的语法、命
令、模块或⾏为变更。如果项⽬中使⽤了⾼版本 CMake 才⽀持的特性(例如特定的函数、⽣成器表达 式、⽬标属性等),⽽⽤⼾本地安装的cmake版本低于项⽬要求的版本,就会出现⽆法解释或者产⽣ 不可预知的⾏为。为了防⽌以上情况出现:
CMake 给我们提供了cmake_minimum_required,这个命令会在配置阶段(cmake命令执⾏
时)检查当前 CMake 版本:
若当前版本低于最低要求,CMake 会直接终⽌并报错,明确提⽰ “需要⾄少 X.X 版本”,避免后
续因版本不兼容导致的模糊错误。
若当前安装的版本满⾜要求,则继续执⾏后续配置流程。
CMake ⾥的 "⽬标" 是什么?
在 CMake 中,“⽬标(Target)” 代表了⼀个需要被⽣成的实体,如可执⾏⽂件、静态库/动态
库等,和Makefile⾥的⽬标是⼀个意思,他是现在CMake⾥最核⼼的3个概念之⼀。(课程第三部分会 详细介绍这些内容)
Step 3:运⾏cmake
#运⾏CMake命令 就在这⼀步 ⽣成Makefile
cmake ..
-- The C compiler identification is AppleClang 17.0.0.17000013
-- The CXX compiler identification is AppleClang 17.0.0.17000013
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
.....
-- Build files have been written to:
/Users/lixiaoshen/Desktop/CMakeDemo/hello_world/build

都是在终端里面运行。

Step 4:编译&&链接
make
[ 50%] Building CXX object CMakeFiles/main.dir/main.cpp.o
[100%] Linking CXX executable main
[100%] Built target main
Step 5:运⾏程序
./hello
lixiaoshen@lixiaoshens-MacBook-Pro build % ./hello
hello world!
lixiaoshen@lixiaoshens-MacBook-Pro build %

三、CMake 命令⾏⼯具介绍

3.1CMake ⼯程构建流程图

块# 1. 创建构建⽬录并进⼊ mkdir build && cd build # 2. 配置项⽬ cmake .. # 3. 构建项⽬ make 或者 cmake --build . # 4. 执⾏测试(如果有) make test 或者 ctest . # 5. 安装项⽬ make install 或者 cmake --install . # 6. ⽣成安装包 make package 或者 cpack # 7 解压 ⽣成的tar 包 tar xvf TestCMakeTools-0.1.1-Linux.tar.gz
Step 0:⽬录结构
├──build
├──CMakeLists.txt
├──main.cpp
└──test.cpp
Step 1:新建⽂件-main.cpp
#include<iostream>
intmain()
{
std::cout <<"hello world!"<< std::endl;
return0;
}
Step 2:新建⽂件-test.cpp
#include<iostream>
#include<cassert>
intmain()
{
assert(1+2==3);
std::cout <<"test passed!"<< std::endl;
return0;
}
Step 3:修改⽂件-CMakeLists.txt
# 1 设置能运⾏此cmake ⼯程的最低cmake版本要求 cmake_minimum_required(VERSION 3.18) # 2 设置项⽬名称 project(helloWorld) # 3 添加构建⽬标 # g++ main.cpp -o main add_executable(main main.cpp) #⽣成测试⼆进制可执⾏程序 add_executable(testAdd test.cpp) # 4 开启测试功能 & 集成测试逻辑 include(CTest) add_test( NAME Case_Add COMMAND testAdd ) # 5 安装⼆进制可执⾏程序到本地 include(GNUInstallDirs) install(TARGETS main) # 6 开启打包功能 & 打包⼆进制可执⾏程序 include(CPack) # cpack 默认收集install 对应的⽬标,然后会把收集到的⽬标 打包在压缩包⾥

3.2⽣成构建系统

通过cmake可以看到cmake命令⽀持的详细参数,常⽤的参数如下:
cmake [options] <path-to-source>
cmake [options] <path-to-existing-build>
cmake [options] -S <path-to-source> -B <path-to-build>

-S:指定源⽂件根⽬录,必须包含⼀个CMakeLists.txt⽂件

-B: 指定构建⽬录,构建⽣成的中间⽂件和⽬标⽂件的⽣成路径,通常会保存⼀个CMakeCache.txt来存储⼀些变量。

源⽂件⽬录 ⽤-S 选项指定
在 CMake 中,源⽂件树(Source Tree) 指的是项⽬源代码的⽬录结构,CMake 通过
CMakeLists.txt ⽂件来组织和管理这个结构。通常使⽤顶层CMakeLists.txt 来标识。
构建⽬录 ⽤ -B 选项指定
在 CMake 中,构建树(Build Tree) 是指项⽬构建过程中⽣成的临时⽂件⽬录,它与源⽂件树(Source Tree) 相对应。构建树包含编译过程中⽣成的中间⽂件(如⽬标⽂件、依赖信息)和最终产物(如可执⾏⽂件、库⽂件)。通常使⽤CMakeCache.txt来标识。
构建时,根据构建中间⽂件是独⽴保存还是放在当前源代码⽬录下, 构建过程分为以下2种:
源内构建:
在源代码树包含的顶级CMakeLists.txt的⽬录下进⾏直接构建。
cmake .
源外构建:
使⽤ -B 参数单独指定⼀个build ⽬录,然后在⼦⽬录⾥制定源⽂件⽬录也就是包含CMakeLists.txt
的⽬录:

cd build && cmake ../隐含./为构建⽬录../为源⽂件⽬录

安装树 install
⽤于正式存放项⽬⽣成的⼆进制程序,静态库,动态库等产物,以便于其他应⽤程序引⽤。
GNUInstallDirs⾥定义个各个系统下的默认安装路径。linux下默认为
prefix =/usr/local
CMAKE_INSTALL_PREFIX=${prefix}

3.3编译链接

cmake --build <dir> = Build a CMake-generated project binary
tree.
⽣成构建⽂件以后,就可以使⽤cmake 来编译链接,也可以使⽤第三⽅构建系统进⾏。因为⽣成
的makefile就在构建树的根⽬录下,所以可以直接在此⽬录运⾏make。
cmake --build ./
或者
make
[ 25%] Building CXX object CMakeFiles/main.dir/main.cpp.o
[ 50%] Linking CXX executable main
[ 50%] Built target main
[ 75%] Building CXX object CMakeFiles/testApp.dir/test.cpp.o
[100%] Linking CXX executable testApp
[100%] Built target testApp

3.4测试

正常我们在编写功能代码之后,也会编写对应的单元测试代码,然后使⽤ctest 来调⽤我们的单元测 试.
Usage
ctest [options]
如果cmake的配置⽂件CMakeLists.txt⾥包含CTest功能,则⽣成的makefile⾥也会包含test 伪⽬标,可以使⽤make 来执⾏。
ctest
或者
maketest
Test project /home/bit/workspace/CMakeClass/cmake_tools/build
Start 1: testAdd
1/1 Test#1: testAdd .......................... Passed 0.00 sec
100% tests passed, 0 tests failed out of 1
Total Test time (real) = 0.00 sec

3.5 安装

cmake --install <dir> = Install a CMake-generated project binary
在单元测试通过之后,我们可以使⽤cmake的 安装命令把库和⼆进制发布到本机的标准路径,供
⼤家⼀起开发使⽤。如果cmake的配置⽂件CMakeLists.txt⾥包含install函数,则⽣成的makefile⾥也会包含install 伪⽬标,可以使⽤make 来执⾏。
cmake --install .
或者
make install
[100%] Built target main
Install the project...
-- Install configuration:""
-- Installing: /usr/local/bin/main

2.6 打包

Usage
cpack [options]
可以使⽤install来本机安装,也可以使⽤cpack 把⼆进制或者动态库打包成压缩包的⽅式进⾏分发
和共享。如果cmake的配置⽂件CMakeLists.txt⾥包含CPack功能,则⽣成的makefile⾥也会包含
package 伪⽬标,可以使⽤make 来执⾏。
cpack 或者 make package CPack: Create package using STGZ CPack: Install projects CPack: - Run preinstall target for: TestCMakeTools CPack: - Install project: TestCMakeTools [] CPack: Create package CPack: - package: /home/bit/workspace/CMakeClass/cmake_tools/build/TestCMakeTools-0.1.1-Linux.sh generated. CPack: Create package using TGZ CPack: Install projects CPack: - Run preinstall target for: TestCMakeTools CPack: - Install project: TestCMakeTools [] CPack: Create package CPack: - package: /home/bit/workspace/CMakeClass/cmake_tools/build/TestCMakeTools-0.1.1- Linux.tar.gz generated. CPack: Create package using TZ CPack: Install projects CPack: - Run preinstall target for: TestCMakeTools CPack: - Install project: TestCMakeTools [] CPack: Create package CPack: - package: /home/bit/workspace/CMakeClass/cmake_tools/build/TestCMakeTools-0.1.1- Linux.tar.Z generated.

3.7 脚本模式

cmake -P <file> = Process script mode.
CMake脚本模式,不会⽣成构建产物,也不会⽣成中间过程。适合处理各种与构建系统⽆关的⾃
动化任务,通过编写简洁的脚本⽂件,你可以实现环境检查、⽂件处理、部署打包等功能。
以下是hello_world ⼯程⾥cmake⽣成⽤于安装⽬标的主makefile代码⽚段,在主makefile⾥使⽤
cmake的脚本模式调⽤了 cmake_install.cmake,在这⾥执⾏⽂件的拷⻉等操作。
# Special rule for the target install
install: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color"--switch=$(COLOR)"--cyan"Install
the project..."
/usr/local/bin/cmake -P cmake_install.cmake
.PHONY : install

2.8 调用外部命令

cmake -E = CMake command mode.
⼀下是hello_world ⼯程⾥主makefile⾥的 RM命令,其实就是使⽤命令模式调⽤了rm -f 外部命令
# The command to remove a file.
RM = /usr/bin/cmake -Erm-f

2.9 查看帮助

cmake --help Usage cmake [options] <path-to-source> cmake [options] <path-to-existing-build> cmake [options] -S <path-to-source> -B <path-to-build> Specify a source directory to (re-)generate a build system for it in the current working directory. Specify an existing build directory to re-generate its build system. Options -S <path-to-source> = Explicitly specify a source directory. -B <path-to-build> = Explicitly specify a build directory. -C <initial-cache> = Pre-load a script to populate the cache. -D <var>[:<type>]=<value> = Create or update a cmake cache entry. -U <globbing_expr> = Remove matching entries from CMake cache. -G <generator-name> = Specify a build system generator. -T <toolset-name> = Specify toolset name if supported by generator. ............