在CMake中,如何使测试目标依赖于默认(全部)目标?

问题描述 投票:0回答:1

我已在 CMake 中启用测试,如下所示:

# ${PROJECT_SOURCE_DIR}/CMakeLists.txt
cmake_minimum_required(VERSION 3.15)
project(hello-world VERSION 0.0.1 LANGUAGES C CXX)

enable_testing()
...

...我添加了这样的测试:

# /home/user/path/to/my/project/src/test/CMakeLists.txt
set(TEST_FILES test.cpp)

add_executable(my-test ${TEST_FILES})

add_test(NAME my-test
  COMMAND my-test --gtest_output=xml:${CMAKE_BINARY_DIR}/TestResult/my-test.xml
  WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})

(我认为添加测试的方法与问题无关,但如果不是,请告诉我;这种添加测试的方法是根据我学习 CMake 的 Udemy 课程中的说明进行的)

有了上面的内容,在构建测试目标之前似乎有必要先构建默认目标(

all
)。 IE。我不能这样做:

$ cmake --build --preset linux --target test
Running tests...
    Start 1: my-test
Could not find executable /home/user/path/to/my/project/src/test/my-test
Looked in the following places:
...

...我需要这样做:

$ cmake --build --preset linux
$ cmake --build --preset linux --target test # this now succeeds

有没有办法让

test
目标依赖于默认(
all
)目标?

根据此 CMake 文档,我的理解是

test
不是自定义目标,即它不是我用
add_custom_target()
显式添加的内容。尽管如此,从像这样的文章Stack Overflow post关于
add_dependencies
的CMake文档,我认为解决方案将添加类似的内容:

add_dependencies(test all)

到顶级 CMakeLists.txt,但这导致了此错误:

$ cmake --preset linux
CMake Error at CMakeLists.txt:30 (add_dependencies):
  Cannot add target-level dependencies to non-existent target "test".

  The add_dependencies works for top-level logical targets created by the
  add_executable, add_library, or add_custom_target commands.  If you want to
  add file-level dependencies see the DEPENDS option of the add_custom_target
  and add_custom_command commands.

我认为我没有添加文件级依赖项,所以我认为错误消息的建议没有帮助。

cmake build-dependencies
1个回答
0
投票

您可以定义一个工作流程预设,其中可以组合配置、构建和运行测试预设。所以你的 CLI 看起来像这样:

cmake --workflow --preset do-everything
© www.soinside.com 2019 - 2024. All rights reserved.