[CMake] Project Structure and add_subdirectory()

Marek Vojtko marek.vojtko at oxidegames.com
Fri Sep 27 12:00:02 EDT 2019


Using add_subdirectory() in a "superbuild" setup is straightforward: Create a root CMakeLists.txt which calls add_subdirectory() on all directories of your project and each target can then use target_link_libraries() without worrying where the target came from.

Unfortunately the "superbuild" setup also means that each target is compiled exactly once, which means that you cannot change a target's build environment per-application (e.g. preprocessor definitions that change the sizes of stack arrays).

If I need per-application control of its dependencies' build environment I can have each application's CMakeLists.txt call add_subdirectory() for all of its dependencies. However, that means that each application now has to know all of its *transitive* dependencies and the application's CMakeLists.txt has to be kept up-to-date with any changes in its dependency tree, no matter how deep. So if AppA depends on LibA, which depends on LibB, which depends on LibC. Not only does AppA's CMakeLists.txt have to call add_subdirectory() on LibA, LibB, and LibC, but if LibC is modified to depend on LibX, now AppA's CMakeLists.txt has to also be modified to call add_subdirectory() on LibX.

Having each target call add_subdirectory() on its own dependencies seems silly, because that would create an insane number of duplicated targets. If LibA depends on LibB and LibC, and both LibB and LibC depend on LibD, this approach would result in both LibB and LibC calling add_subdirectory() on LibD, creating the target twice, which would likely not compile.

Are these my only two options? Either:
- use a superbuild to have CMake handle my transitive dependencies, but give up per-application build environment changes, or
- track all transitive dependencies manually in each application's CMakeLists.txt, but retain the ability to change the build environment per application.


More information about the CMake mailing list