CMake where one can build from the directory itself or from the root cmake


I have a question about using CMake for a repository, with a root cmake at the top which add_subdirectory()'s all the directories. However, I would also like to be able to build from individual directories without resorting to add_subdirectory on a non subdirectory, which sometimes messes up the build layout - e.g.





add_library(lib1 ...)


add_subdirectory(../lib1 ${PROJECT_BINARY_DIR}/lib1) #!!!

target_link_libraries(program1 lib1)

[An issue with this is if I set EXCLUDE_FROM_ALL on lib1 in the root cmake, lib1 ends up being built in /program1/lib1]

Is it possible to:

  1. Write the CMakeLists.txt in such a way to be able to build program1 from the program1 folder instead of the root without have to resort to the ugly add_subdirectory(../lib1 ${PROJECT_BINARY_DIR}/lib1)
  2. Build only selected targets from the root cmake without needing the dependencies of other subdirectories? e.g. if /lib2 requires some dependency that I don’t have on my system, but I only want to build program1 (which also builds lib1) - is this possible from the root?

Thank you!

No, there’s no built-in way to do such things. I’d recommend figuring out what you want your project lines to be and structure the repo that way. Supporting arbitrary root directories isn’t really worth it IME because your “how to build” docs get really complicated (or you make “anything” work and the code is really complicated).