[CMake] Forcing a target to be built if another target is built

Job Noorman job at noorman.info
Wed May 9 08:51:22 EDT 2018


Hi all,

We have a large codebase consisting of 200+ modules. Each module is 
defined in its own subdirectory and compiled as a static library.

These modules are not final products on their own but are combined to 
create "projects". We have about 15 projects that all use a subset of 
the modules to implement their functionality. The projects are 
independent in the sense that they cannot be built together; when 
running cmake, we select the project to build.

To ensure that only the modules that are needed by the selected project 
are built, we took the following approach: all modules have a common 
root directory which is included using add_subdirectory with the 
EXCLUDE_FROM_ALL flag. Then, the current project's root directory is 
added without this flag. This ensures that the targets defined by the 
project and the modules that they need (but no other) are added to the 
build system. This works very well and is much nicer than having to 
define options for all optional modules to be able to disable them.

There is one catch, however: each module defines an executable that runs 
its unit tests. What should happen is that if a module is built by a 
project, its unit tests are also built. However, there seems to be no 
way to define this relationship in CMake. What we would like to express 
is that "if library A is built, then executable ATest should also be 
built". Since ATest obviously links against A, we cannot use 
add_dependencies(A ATest) since this creates a circular dependency 
between an executable and a library.

Note that the "option" approach briefly mentioned above would allow us 
to express this but this would be completely unwieldy in our case.

Is there currently a way in CMake to express this relation between a 
library and an executable?

If not, would the following suggestion make sense?: A target property 
"INTERFACE_DEPENDENCIES" could be added that would set the 
MANUALLY_ADDED_DEPENDENCIES target property of dependents. Setting this 
property on A with ATest as value would then solve my problem (note that 
I proposed adding this property for a different use case here: 
https://gitlab.kitware.com/cmake/cmake/issues/14633).

Regards,
Job



More information about the CMake mailing list