8

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?

PaulR
  • 706
  • 9
  • 27
  • 1
    To prevent the tests being built, ask your build system to just build the library target. The point of having multiple targets is that you can build them independently. You don't have to always build "*all*" or "*install*". – Jesper Juhl Nov 17 '19 at 17:42
  • Thanks, I'll add info to the question to see if this can be expanded upon. – PaulR Nov 17 '19 at 17:45

2 Answers2

5

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)
Former contributor
  • 2,466
  • 2
  • 10
  • 15
4

In addition to Pedro's answer CMake allows us to set EXCLUDE_FROM_ALL when including a subdirectory in the parent project:

add_subdirectory(my_lib my_lib-build EXCLUDE_FROM_ALL)

... which importantly does not exclude any dependencies:

Note that inter-target dependencies supersede this exclusion. If a target built by the parent project depends on a target in the subdirectory, the dependee target will be included in the parent project build system to satisfy the dependency.

add_subdirectory

PaulR
  • 706
  • 9
  • 27