Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 782
PaulR Avatar asked Nov 17 '19 17:11

PaulR


2 Answers

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)
like image 153
Former contributor Avatar answered Oct 24 '22 03:10

Former contributor


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

like image 42
PaulR Avatar answered Oct 24 '22 05:10

PaulR