I have this code project can be built either independently or as a subproject of a larger repository (checking it our as a sub-repository). In the latter case, I have a top-level CMakeLists.txt for the main project which has
add_subdirectory(${MY_SUBPROJ_SUBDIR})
now, I want the subproject to behave somewhat differently in case it's used via the add_directory(). Obviously, I would be using a large if instruction. But what condition do I check? How can CMake "tell", when running for some CMakeLists.txt, whether it's a subdir file or the main file?
After the
project()call in project'sCMakeLists.txtand in the project's subdirectories you may use:NOTE: As stated in the comments, this approach may to not work on Windows, where
CMAKE_SOURCE_DIRcontains lower-case version ofPROJECT_SOURCE_DIRand thus cannot be compared directly for equality. For that case approach with checkingPARENT_DIRECTORYproperty, as described in that answer to the duplicate question, seems to be more robust.Alternative for use before the
project()call:This alternative can also be used anywhere in project's
CMakeLists.txt(but not in subdirectories).Assume you have a project A with two
CMakeLists.txt: one in the project's directory, and one in subdirectorysrc/. Scheme for use approaches described above:CMakeLists.txt:
src/CMakeLists.txt:
With given scheme project A may detect, whether it is built standalone (top-level project) or as a part of another project B.