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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With