0

Given a big cmake project, let B be a CMakeLists.txt, located at some directory within it. Is there any way to print (message(...)) from within B which parent CMakeLists.txt file did the add_subdirectory(B) or equivalent?

Note: Let's suppose that no cmake files do literally add_subdirectory(B), but rather add_subdirectory(${X}), being X the path to subdirectory B, determined through the cmake tree somehow. Otherwise, this could be determined just with grep.

Dan
  • 2,452
  • 20
  • 45

1 Answers1

2

Property PARENT_DIRECTORY contains parent source directory:

get_directory_property(parent_dir PARENT_DIRECTORY)
if (parent_dir)
    message(STATUS "I am called with 'add_subdirectory' from script ${parent_dir}/CMakeLists.txt")
else ()
    message(STATUS "I am top-level CMakeLists.txt script)
endif()

See also How to detect if current scope has a parent in CMake?

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • 1
    If the child CMake file was added via `include()` or `find_package()`, the `PARENT_DIRECTORY` property will also return empty string. So for these cases, you can instead use [`CMAKE_PARENT_LIST_FILE`](https://cmake.org/cmake/help/v3.18/variable/CMAKE_PARENT_LIST_FILE.html) to obtain the full path to the parent CMakeLists.txt file. – Kevin Sep 14 '20 at 13:42
  • Yes, `PARENT_DIRECTORY` works only for inclusion via `add_subdirectory()`. And `CMAKE_PARENT_LIST_FILE` works only for inclusions via `include()` and `find_package()`. – Tsyvarev Sep 14 '20 at 13:46