Search code examples
c++testingcmakesubdirectorydoctest

CMake: prevent building test executable target in subdirectory library project


I have written a small library that uses doctest. In CMakeLists.txt I have:

...

add_library(my_lib STATIC ${SRCS} $<TARGET_OBJECTS:common_files>)
add_executable(tests ${SRCS} $<TARGET_OBJECTS:common_files>)
target_compile_definitions(my_lib PRIVATE -DDOCTEST_CONFIG_DISABLE)

...

When using the library in a project via add_subdirectory, the library and the test executable are built when I just need the library.

What can I do to prevent tests being built when including the CMakeLists.txt as a subdirectory, or is there a better way of achieving a similar result?

I am using Ninja to build the project.

I can check targets with ninja -t targets and build only the ones I want from the command line, but can I get CMake to exclude tests in subdirectories from the all target?


Solution

  • If I understood you correctly, this is exactly what the CMake property EXCLUDE_FROM_ALL does. It can be used as a target property (if you want to exclude only that target), or as a directory property to exclude all the targets in a subdirectory. To set this property for your target:

    set_target_properties(tests PROPERTIES EXCLUDE_FROM_ALL True)