cmake:如何分别编译生产代码和测试代码

cmake: how to separately compile production code and test code

我阅读了 this brilliant tutorial 如何将 Google Test 与 CMake 集成。那里的项目大纲如下所示:

+-- CMakeLists.txt
+-- main
|    +-- CMakeLists
|    +-- main.cpp
|
+-- test
|    +-- CMakeLists.txt
|    +-- testfoo
|       +-- CMakeLists.txt
|       +-- main.cpp
|       +-- testfoo.h
|       +-- testfoo.cpp
|       +-- mockbar.h
|
+-- libfoo
|    +-- CMakeLists.txt
|    +-- foo.h
|    +-- foo.cpp
|
+-- libbar
     +-- CMakeLists.txt
     +-- bar.h
     +-- bar.cpp

(有兴趣的可以从here中查看该示例项目的全部代码)

顶级 CMakeLists.txt 包含(除其他外)语句 enable_testing()add_subdirectory(test)。编译和 运行 测试用例与此设置完美配合,只需 运行

mkdir build && cd build
cmake ..
make
make test

但是我如何将这个项目编译成生产代码,即只有组件 testlibfoolibbar,而不进行所有单元测试?

我是否应该使语句 enable_testing()add_subdirectory(test) 以某种方式依赖于某些构建配置变量?或者对此的最佳做法是什么?

我所做的是为创建单元测试创​​建一个自定义宏,它执行以下操作:

set_target_properties(${NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/test)

然后你的测试将在一个特殊目录 (test) 而不是常规目录(通常是 bin)中结束。然后对于生产,您只需复制没有测试目录的常规目录。

为了仅根据要求构建测试,我是这样做的:

  1. 添加一个选项option(BUILD_TEST "Build the unit tests" ON)
  2. 仅在 BUILD_TEST 开启时包含测试子目录

if(BUILD_TEST) add_subdirectory(test) endif()

在您的情况下,您可以将其修改为 testfoo。

如您要求生产,您可以使用以下代替仅在调试模式下构建:

if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") add_subdirectory(test) endif()