如何添加 CMake 自定义目标来测试所有子项目?

How to add a CMake custom target to test all sub-projects?

我有一个存储库,里面有几个项目。生成的目录结构如下:

Repository
  --CMakeLists.txt
  --Project A
      --CMakeLists.txt
  --Project B
      --CMakeLists.txt

在项目 A 和 B 中,我使用 add_test 添加了测试。在项目内部时,我可以做 make test

如何将目标 "test" 添加到顶部 CMakeLists.txt 以便能够从顶部目录调用 make test 并执行所有项目的测试?

我刚刚尝试使用以下文件重现您的设置:

/tmp/test $ tree
.
├── a
│   └── CMakeLists.txt
├── b
│   └── CMakeLists.txt
└── CMakeLists.txt

/tmp/test $ cat CMakeLists.txt 
cmake_minimum_required(VERSION 3.0)

project(Foo)

enable_testing()
add_subdirectory(a)
add_subdirectory(b)
/tmp/test $ cat a/CMakeLists.txt 
project(A)
add_test(NAME atest COMMAND echo "hello from a")
/tmp/test $ cat b/CMakeLists.txt 
project(B)
add_test(NAME btest COMMAND echo "hello from b")

/tmp/test/build $ mkdir build && cd build
/tmp/test/build $ cmake .. && make test
# Remove some output
Running tests...
Test project /tmp/test/build
    Start 1: atest
1/2 Test #1: atest ............................   Passed    0.00 sec
    Start 2: btest
2/2 Test #2: btest ............................   Passed    0.00 sec