In CMake, how to make the test target depend on the default (all) target?

36 views Asked by At

I've enabled testing in CMake as follows:

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

enable_testing()
...

...and I've added tests like this:

# /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})

(I think that the method of adding tests is not relevant to the question, but please let me know if otherwise; this method for adding tests is per instruction from the Udemy course from which I learned CMake)

With the above, it seems necessary to build the default target (all) first before building the test target. I.e. I cannot do this:

$ 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:
...

...I need to do this:

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

Is there a way to make the test target depend on the default (all) target?

Per this CMake documentation, my understanding is that test is not a custom target, i.e. it's not something I explicitly added with a add_custom_target(). Nevertheless, from articles like this Stack Overflow post and the CMake documentation on add_dependencies, I thought the solution would be adding something like:

add_dependencies(test all)

to the top-level CMakeLists.txt, but that resulted in this error:

$ 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.

I don't think I'm adding file-level dependencies, so I don't think the error message's suggestion is helpful.

1

There are 1 answers

0
zaufi On

You can define a workflow preset where can combine configuration, build, and run test presets. So your CLI gonna look like this:

cmake --workflow --preset do-everything