# 第5章 配置时和构建时的操作

本章的主要内容有：

* 使用平台无关的文件操作
* 配置时运行自定义命令
* 构建时运行自定义命令:Ⅰ. 使用add\_custom\_command
* 构建时运行自定义命令:Ⅱ. 使用add\_custom\_target
* 构建时为特定目标运行自定义命令
* 探究编译和链接命令
* 探究编译器标志命令
* 探究可执行命令
* 使用生成器表达式微调配置和编译

我们将学习如何在配置和构建时，执行自定义操作。先简单回顾一下，与CMake工作流程相关的时序:

1. **CMake时**或**构建时**：CMake正在运行，并处理项目中的`CMakeLists.txt`文件。
2. **生成时**：生成构建工具(如Makefile或Visual Studio项目文件)。
3. **构建时**：由CMake生成相应平台的原生构建脚本，在脚本中调用原生工具构建。此时，将调用编译器在特定的构建目录中构建目标(可执行文件和库)。
4. **CTest时**或**测试时**：运行测试套件以检查目标是否按预期执行。
5. **CDash时**或**报告时**：当测试结果上传到仪表板上，与其他开发人员共享测试报告。
6. **安装时**：当目标、源文件、可执行程序和库，从构建目录安装到相应位置。
7. **CPack时**或**打包时**：将项目打包用以分发时，可以是源码，也可以是二进制。
8. **包安装时**：新生成的包在系统范围内安装。

完整的工作流程和对应的时序，如下图所示:

![](/files/-LmKs9Mq3NYlLAVC0eH6)

本章会介绍在配置和构建时的自定义行为，我们将学习如何使用这些命令:

* **execute\_process**，从CMake中执行任意进程，并检索它们的输出。
* **add\_custom\_target**，创建执行自定义命令的目标。
* **add\_custom\_command**，指定必须执行的命令，以生成文件或在其他目标的特定生成事件中生成。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chenxiaowei.gitbook.io/cmake-cookbook/5.0-chinese.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
