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

Hi,

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.

/CMakeLists.txt

project(main)

add_subdirectory(lib1/)
add_subdirectory(lib2/) 
add_subdirectory(program1/)
add_subdirectory(program2/)

/lib1/CMakeLists.txt

project(lib1)
add_library(lib1 ...)

/program1/CMakeLists.txt

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

add_executable(program1)
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).