CMake使用教程(二)

3,474 阅读6分钟

CMake 是一种跨平台的免费开源软件工具,用于使用与编译器无关的方法来管理软件的构建过程。在 Android Studio 上进行 NDK 开发默认就是使用 CMake 管理 C/C++ 代码,因此在学习 NDK 之前最好对 CMake 有一定的了解。

本文主要以翻译 CMake官方教程文档为主,加上自己的一些理解,该教程涵盖了 CMake 的常见使用场景。由于能力有限,翻译部分采用机翻+人工校对,翻译有问题的地方,说声抱歉。

开发环境:

  • macOS 10.14.6
  • CMake 3.15.1
  • CLion 2018.2.4

添加“库”的使用要求

示例程序地址

使用要求可以更好地控制库或可执行文件的链接和包含行,同时还可以更好地控制 CMake 内部目标的传递属性。利用使用要求的主要命令是:

  • target_compile_definitions

    给指定目标添加编译定义。

  • target_compile_options

    给指定目标添加编译选项。

  • target_include_directories

    给指定目标添加包含目录。

  • target_link_libraries

    指定链接给定目标或其依赖项时要使用的库或标志。

控制 CMake 内部目标的传递属性有三种类型:

  • PRIVATE

    属性只应用到本目标,不应用到链接本目标的目标。即生产者需要,消费者不需要。

  • PUBLIC

    属性既应用到本目标也应用到链接目标的目标。即生产者和消费者都需要。

  • INTERFACE

    属性不应用到本目标,应用到链接本目标的目标。即生产者不需要,消费者需要。

让我们重构代码“提供选项”项目的代码,以使用现代 CMake 的使用要求方法。我们首先声明,链接到 MathFunctions 的任何人都需要包含当前源目录,而 MathFunctions 本身不需要。因此,这里使用 INTERFACE

将以下行添加到 MathFunctions/CMakeLists.txt 的末尾:

# state that anybody linking to us needs to include the current source dir
# to find MathFunctions.h, while we don't.
# 说明与我们链接的任何人都需要包含当前源目录才能找到 MathFunctions.h,而我们不需要。
target_include_directories(MathFunctions
        INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
        )

现在,我们已经指定了 MathFunction 的使用要求,我们可以安全地从顶级 CMakeLists.txt 中删除对 EXTRA_INCLUDES变量的使用:

if(USE_MYMATH)
  add_subdirectory(MathFunctions)
  list(APPEND EXTRA_LIBS MathFunctions)
endif()

target_include_directories(Tutorial PUBLIC
        "${PROJECT_BINARY_DIR}"
        )

在项目根目录运行命令编译项目和生成可执行文件:

cmake -B cmake-build-debug
cmake --build cmake-build-debug

在项目根目录运行生成的可执行文件:

./cmake-build-debug/Tutorial 2

终端输出:

Computing sqrt of 2 to be 1.5
Computing sqrt of 2 to be 1.41667
Computing sqrt of 2 to be 1.41422
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
The square root of 2 is 1.41421

安装

示例程序地址

安装规则非常简单:对于 MathFunctions ,我们要安装库和头文件,对于应用程序,我们要安装可执行文件和配置的头文件。

因此,在 MathFunctions/CMakeLists.txt 的末尾添加:

# install rules
# 安装规则
install(TARGETS MathFunctions DESTINATION lib)
install(FILES MathFunctions.h DESTINATION include)

并在顶级 CMakeLists.txt 的末尾添加:

# add the install targets
# 添加安装规则
install(TARGETS Tutorial DESTINATION bin)
install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
        DESTINATION include
        )

这就是本地安装所需的全部。

在项目根目录运行命令编译项目和生成可执行文件:

cmake -B cmake-build-debug
cmake --build cmake-build-debug

在项目根目录运行命令安装可执行文件:

 cmake --install cmake-build-debug

CMake 从3.15开始使用 cmake --install 安装文件。CMake 变量 CMAKE_INSTALL_PREFIX 用于确定文件的安装根目录。如果使用 cmake --install,则可以通过 --prefix 参数指定自定义安装目录。对于多配置工具,请使用 --config 参数指定配置。

终端输出:

-- Install configuration: ""
-- Installing: /usr/local/lib/libMathFunctions.a
-- Installing: /usr/local/include/MathFunctions.h
-- Installing: /usr/local/bin/Tutorial
-- Installing: /usr/local/include/TutorialConfig.h

在项目根目录执行命令:

Tutorial 2

终端输出:

Computing sqrt of 2 to be 1.5
Computing sqrt of 2 to be 1.41667
Computing sqrt of 2 to be 1.41422
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
The square root of 2 is 1.41421

这个时候我们调用的不是 cmake-build-debug 下的 Tutorial 文件,而是安装到 /usr/local/bin 目录下的 Tutorial 文件。我们可以通过命令查看一下 Tutorial 的位置:

where Tutorial

终端输出:

/usr/local/bin/Tutorial

测试

示例程序地址

接下来,测试我们的应用程序。在顶级 CMakeLists 文件的末尾,我们可以启用测试,然后添加一些基本测试以验证应用程序是否正常运行。

# enable testing
# 启用测试
enable_testing()

# does the application run
# 测试应用程序是否运行
add_test(NAME Runs COMMAND Tutorial 25)

# does the usage message work?
# 测试消息是否工作?
add_test(NAME Usage COMMAND Tutorial)
set_tests_properties(Usage
        PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
        )

# define a function to simplify adding tests
# 定义一个函数以简化添加测试
function(do_test target arg result)
    add_test(NAME Comp${arg} COMMAND ${target} ${arg})
    set_tests_properties(Comp${arg}
            PROPERTIES PASS_REGULAR_EXPRESSION ${result}
            )
endfunction(do_test)

# do a bunch of result based tests
# 做一堆基于结果的测试
do_test(Tutorial 4 "4 is 2")
do_test(Tutorial 9 "9 is 3")
do_test(Tutorial 5 "5 is 2.236")
do_test(Tutorial 7 "7 is 2.645")
do_test(Tutorial 25 "25 is 5")
do_test(Tutorial -25 "-25 is [-nan|nan|0]")
do_test(Tutorial 0.0001 "0.0001 is 0.01")

第一个测试只是验证应用程序正在运行,没有段错误或其他崩溃,并且返回值为零。这是 CTest 测试的基本形式。

下一个测试使用 PASS_REGULAR_EXPRESSION 测试属性来验证测试的输出是否包含某些字符串。在这种情况下,验证在提供了错误数量的参数时是否打印了用法消息。

最后,我们有一个名为 do_test 的函数,该函数运行应用程序并验证所计算的平方根对于给定输入是否正确。对于 do_test 的每次调用,都会基于传递的参数将另一个测试添加到项目中,该测试具有名称,输入和预期结果。

在项目根目录运行命令编译项目和生成可执行文件:

cmake -B cmake-build-debug
cmake --build cmake-build-debug

在项目根目录运行命令测试应用程序:

cd cmake-build-debug
ctest

终端输出:

Test project /Users/taylor/Project/Taylor/C/Study/cmake-tutorial/cmake-test/cmake-build-debug
    Start 1: Runs
1/9 Test #1: Runs .............................   Passed    0.00 sec
    Start 2: Usage
2/9 Test #2: Usage ............................   Passed    0.00 sec
    Start 3: Comp4
3/9 Test #3: Comp4 ............................   Passed    0.00 sec
    Start 4: Comp9
4/9 Test #4: Comp9 ............................   Passed    0.00 sec
    Start 5: Comp5
5/9 Test #5: Comp5 ............................   Passed    0.00 sec
    Start 6: Comp7
6/9 Test #6: Comp7 ............................   Passed    0.00 sec
    Start 7: Comp25
7/9 Test #7: Comp25 ...........................   Passed    0.00 sec
    Start 8: Comp-25
8/9 Test #8: Comp-25 ..........................   Passed    0.00 sec
    Start 9: Comp0.0001
9/9 Test #9: Comp0.0001 .......................   Passed    0.00 sec

100% tests passed, 0 tests failed out of 9

Total Test time (real) =   0.03 sec

系统自检

示例程序地址

让我们考虑向我们的项目中添加一些代码,这些代码取决于目标平台可能不具备的功能。

对于此示例,我们将添加一些代码,具体取决于目标平台是否具有 logexp 函数。当然,几乎每个平台都具有这些功能,但对于本教程而言,假定它们并不常见。

如果平台具有 logexp ,那么我们将使用它们来计算 mysqrt 函数中的平方根。我们首先在顶级 CMakeList 中使用 CheckSymbolExists.cmake 宏测试这些功能的可用性。

# does this system provide the log and exp functions?
# 该系统是否提供log和exp函数?
include(CheckSymbolExists)
set(CMAKE_REQUIRED_LIBRARIES "m")
check_symbol_exists(log "math.h" HAVE_LOG)
check_symbol_exists(exp "math.h" HAVE_EXP)

TutorialConfig.hconfigure_file 命令之前完成对 logexp 的测试非常重要,configure_file 命令使用 CMake 中的当前设置立即配置文件,所以 check_symbol_exists 命令应该放在 configure_file 之前。

现在,将这些定义添加到 TutorialConfig.h.in 中,以便我们可以从 mysqrt.cxx中使用它们:

// does the platform provide exp and log functions?
// 平台是否提供log和exp函数?
#cmakedefine HAVE_LOG
#cmakedefine HAVE_EXP

更新 MathFunctions/CMakeLists.txt 文件,以便 mysqrt.cxx知道此文件的位置:

target_include_directories(MathFunctions
          INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
          PRIVATE ${CMAKE_BINARY_DIR}
          )

修改 mysqrt.cxx 以包含 cmathTutorialConfig.h。接下来,在 mysqrt函数的同一文件中,我们可以使用以下代码(如果在系统上可用)提供基于 logexp 的替代实现(在返回结果前不要忘记 #endif !):

我们将在 TutorialConfig.h.in 中使用新定义,因此请确保在配置该文件之前进行设置。

#if defined(HAVE_LOG) && defined(HAVE_EXP)
    double result = exp(log(x) * 0.5);
    std::cout << "Computing sqrt of " << x << " to be " << result
              << " using log and exp" << std::endl;
#else
    double result = x;
    // do ten iterations
    for (int i = 0; i < 10; ++i) {
        if (result <= 0) {
            result = 0.1;
        }
        double delta = x - (result * result);
        result = result + 0.5 * delta / result;
        std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
    }
#endif

在项目根目录运行命令编译项目和生成可执行文件:

cmake -B cmake-build-debug
cmake --build cmake-build-debug

在项目根目录运行生成的可执行文件:

./cmake-build-debug/Tutorial 2

终端输出:

Computing sqrt of 2 to be 1.41421 using log and exp
The square root of 2 is 1.41421

CMake使用教程系列文章