> For the complete documentation index, see [llms.txt](https://chenxiaowei.gitbook.io/cmake-cookbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://chenxiaowei.gitbook.io/cmake-cookbook/7.0-chinese/7.1-chinese.md).

# 7.1 使用函数和宏重用代码

**NOTE**:*此示例代码可以在* <https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-7/recipe-01> *中找到，其中包含一个C++例子。该示例在CMake 3.5版(或更高版本)中是有效的，并且已经在GNU/Linux、macOS和Windows上进行过测试。*

任何编程语言中，函数允许我们抽象(隐藏)细节并避免代码重复，CMake也不例外。本示例中，我们将以宏和函数为例进行讨论，并介绍一个宏，以便方便地定义测试和设置测试的顺序。我们的目标是定义一个宏，能够替换`add_test`和`set_tests_properties`，用于定义每组和设置每个测试的预期开销(第4章，第8节)。

## 准备工作

我们将基于第4章第2节中的例子。`main.cpp`、`sum_integers.cpp`和`sum_integers.hpp`文件不变，用来计算命令行参数提供的整数队列的和。单元测试(`test.cpp`)的源代码也没有改变。我们还需要Catch 2头文件，`catch.hpp`。与第4章相反，我们将把源文件放到子目录中，并形成以下文件树(稍后我们将讨论CMake代码):

```
.
├── CMakeLists.txt
├── src
│     ├── CMakeLists.txt
│     ├── main.cpp
│     ├── sum_integers.cpp
│     └── sum_integers.hpp
└── tests
      ├── catch.hpp
      ├── CMakeLists.txt
      └── test.cpp
```

## 具体实施

1. 定义了CMake最低版本、项目名称和支持的语言，并要求支持C++11标准:

   ```
   cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
   project(recipe-01 LANGUAGES CXX)
   set(CMAKE_CXX_STANDARD 11)
   set(CMAKE_CXX_EXTENSIONS OFF)
   set(CMAKE_CXX_STANDARD_REQUIRED ON)
   ```
2. 根据GNU标准定义`binary`和`library`路径:

   ```
   include(GNUInstallDirs)

   set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY
       ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR})
   set(CMAKE_LIBRARY_OUTPUT_DIRECTORY
       ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR})
   set(CMAKE_RUNTIME_OUTPUT_DIRECTORY
       ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR})
   ```
3. 最后，使用`add_subdirectory`调用`src/CMakeLists.txt`和`tests/CMakeLists.txt`:

   ```
   add_subdirectory(src)
   enable_testing()
   add_subdirectory(tests)
   ```
4. `src/CMakeLists.txt`定义了源码目标:

   ```
   set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
   add_library(sum_integers sum_integers.cpp)
   add_executable(sum_up main.cpp)
   target_link_libraries(sum_up sum_integers)
   ```
5. `tests/CMakeLists.txt`中，构建并链接`cpp_test`可执行文件:

   ```
   add_executable(cpp_test test.cpp)
   target_link_libraries(cpp_test sum_integers)
   ```
6. 定义一个新宏`add_catch_test`:

   ```
   macro(add_catch_test _name _cost)
     math(EXPR num_macro_calls "${num_macro_calls} + 1")
     message(STATUS "add_catch_test called with ${ARGC} arguments: ${ARGV}")

     set(_argn "${ARGN}")
     if(_argn)
         message(STATUS "oops - macro received argument(s) we did not expect: ${ARGN}")
     endif()

     add_test(
       NAME
         ${_name}
       COMMAND
         $<TARGET_FILE:cpp_test>
       [${_name}] --success --out
       ${PROJECT_BINARY_DIR}/tests/${_name}.log --durations yes
       WORKING_DIRECTORY
         ${CMAKE_CURRENT_BINARY_DIR}
       )

     set_tests_properties(
       ${_name}
       PROPERTIES
           COST ${_cost}
       )
   endmacro()
   ```
7. 最后，使用`add_catch_test`定义了两个测试。此外，还设置和打印了变量的值:

   ```
   set(num_macro_calls 0)
   add_catch_test(short 1.5)
   add_catch_test(long 2.5 extra_argument)
   message(STATUS "in total there were ${num_macro_calls} calls to add_catch_test")
   ```
8. 现在，进行测试。配置项目(输出行如下所示):

   ```
   $ mkdir -p build
   $ cd build
   $ cmake ..

   -- ...
   -- add_catch_test called with 2 arguments: short;1.5
   -- add_catch_test called with 3 arguments: long;2.5;extra_argument
   -- oops - macro received argument(s) we did not expect: extra_argument
   -- in total there were 2 calls to add_catch_test
   -- ...
   ```
9. 最后，构建并运行测试:

   ```
   $ cmake --build .
   $ ctest
   ```
10. 长时间的测试会先开始:

    ```
    Start 2: long
    1/2 Test #2: long ............................. Passed 0.00 sec
    Start 1: short
    2/2 Test #1: short ............................ Passed 0.00 sec

    100% tests passed, 0 tests failed out of 2
    ```

## 工作原理

这个配置中的新添加了`add_catch_test`宏。这个宏需要两个参数`_name`和`_cost`，可以在宏中使用这些参数来调用`add_test`和`set_tests_properties`。参数前面的下划线，是为了向读者表明这些参数只能在宏中访问。另外，宏自动填充了`${ARGC}`(参数数量)和`${ARGV}`(参数列表)，我们可以在输出中验证了这一点:

```
-- add_catch_test called with 2 arguments: short;1.5
-- add_catch_test called with 3 arguments: long;2.5;extra_argument
```

宏还定义了`${ARGN}`，用于保存最后一个参数之后的参数列表。此外，我们还可以使用`${ARGV0}`、`${ARGV1}`等来处理参数。我们演示一下，如何捕捉到调用中的额外参数(`extra_argument`):

```
add_catch_test(long 2.5 extra_argument)
```

我们使用了以下方法:

```
set(_argn "${ARGN}")
if(_argn)
    message(STATUS "oops - macro received argument(s) we did not expect: ${ARGN}")
endif()
```

这个`if`语句中，我们引入一个新变量，但不能直接查询`ARGN`，因为它不是通常意义上的CMake变量。使用这个宏，我们可以通过它们的名称和命令来定义测试，还可以指示预期的开销，这会让耗时长的测试在耗时短测试之前启动，这要归功于`COST`属性。

我们可以用一个函数来实现它，而不是使用相同语法的宏:

```
function(add_catch_test _name _cost)
    ...
endfunction()
```

宏和函数之间的区别在于它们的变量范围。宏在调用者的范围内执行，而函数有自己的变量范围。换句话说，如果我们使用宏，需要设置或修改对调用者可用的变量。如果不去设置或修改输出变量，最好使用函数。我们注意到，可以在函数中修改父作用域变量，但这必须使用`PARENT_SCOPE`显式表示:

```
set(variable_visible_outside "some value" PARENT_SCOPE)
```

为了演示作用域，我们在定义宏之后编写了以下调用:

```
set(num_macro_calls 0)
add_catch_test(short 1.5)
add_catch_test(long 2.5 extra_argument)
message(STATUS "in total there were ${num_macro_calls} calls to add_catch_test")
```

在宏内部，将`num_macro_calls`加1:

```
math(EXPR num_macro_calls "${num_macro_calls} + 1")
```

这时产生的输出:

```
-- in total there were 2 calls to add_catch_test
```

如果我们将宏更改为函数，测试仍然可以工作，但是`num_macro_calls`在父范围内的所有调用中始终为0。将CMake宏想象成类似函数是很有用的，这些函数被直接替换到它们被调用的地方(在C语言中内联)。将CMake函数想象成黑盒函数很有必要。黑盒中，除非显式地将其定义为`PARENT_SCOPE`，否则不会返回任何内容。CMake中的函数没有返回值。

## 更多信息

可以在宏中嵌套函数调用，也可以在函数中嵌套宏调用，但是这就需要仔细考虑变量的作用范围。如果功能可以使用函数实现，那么这可能比宏更好，因为它对父范围状态提供了更多的默认控制。

我们还应该提到在`src/cmakelist .txt`中使用`CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE`:

```
set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
```

这个命令会将当前目录，添加到`CMakeLists.txt`中定义的所有目标的`interface_include_directory`属性中。换句话说，我们不需要使用`target_include_directory`来添加`cpp_test`所需头文件的位置。
