CMake Help
系列基于CMake Tutorial
本文基于Step 1: A Basic Starting Point
环境Apple clang version 14.0.0 (clang-1400.0.29.202)以及cmake version 3.25.0
一些可以参考的资料learnCmake,An Introduction to Modern CMake
利用CMake构建一个简单的可执行文件。
一个简单的HelloWorld
1 | mkdir simpleProject && cd simpleProject |
在main.cpp
中写入
1 |
|
简单的CMakeLists.txt
的编写
编辑CMakeLists.txt
文件写入
1 | cmake_minimum_required(VERSION 3.25.0) # CMake最低版本要求 VERSION >= 3.25.0 |
简单的解释,从main.cpp
中编译链接生成target1
可执行程序。
终端下
1 | cmake -B build |
称为配置阶段(configure)。检测环境并生成构建规则,并在build
目录下生成本地构建系统能识别的项目文件。
使用终端命令ls
可以看到项目目录下生成了一个build
文件夹
下一步,为构建阶段(build)。
1 | cmake --build build |
CMake
程序会进入./build
构建生成目标可执行文件target1
。可以在终端中
1 | ./build/target1 |
Hello World!
指定C++标准以及配置项目版本号
指定C++标准,在CMakeLists.txt
中添加一行
1 | # 设置c++标准为C++17标准 |
配置项目版本号
修改CMakeLists.txt
的中的project(MyProjetc)
为project(MyProjetc VERSION 1.0.0)
Sometimes it may be useful to have a variable that is defined in your CMakelists.txt file also be available in your source code. In this case, we would like to print the project version.
One way to accomplish this is by using a configured header file. We create an input file with one or more variables to replace. These variables have special syntax which looks like @VAR@. Then, we use the configure_file() command to copy the input file to a given output file and replace these variables with the current value of VAR in the CMakelists.txt file.
生成配置头文件
创建文件MyProject.h.in
并写入以下内容
1 |
向CMakeLists.txt
添加
1 | configure_file("MyProject.h.in" |
Cmake
在配置阶段会根据MyProject.h.in
文件和版本号自动生成MyProject.h
文件,里面是项目版本号的宏定义。
1 | cmake -B build |
会在项目二进制目录目录下会生成一个头文件MyProject.h
,在CMake
中有保留变量PROJECT_BINARY_DIR
指示目录位置。在这个例子中为build
目录。
在项目中使用,修改CMakelists.txt
1 | # 指定目标target1包含的头文件路径 |
CMake分离编译
目录结构
仍旧在simpleProject
目录下,创建两文件hello.h
和hello.cpp
。
除去build
文件夹,目录结构为
1 | . |
向hello.h
文件写入
1 |
|
声明了一个函数,在hello.cpp
中实现
1 |
|
在main.cpp
中调用
1 |
|
CMakelists.txt
文件为
1 | # CMake最低版本要求 VERSION >= 3.25.0 |
最后构建
1 | cmake -B build && cmake --build build && ./build/target1 |