Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the name of the parent project in CMake?

Please see the below minimal example:

├───CMakeLists.txt
├───bar
│   ├───CMakeLists.txt

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)
project(foo)
add_subdirectory(bar)

bar/CMakeLists.txt

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

project(bar)
cmake_path(GET CMAKE_CURRENT_LIST_DIR PARENT_PATH BAR_PARENT_DIR)
# how can I get `foo` given ${BAR_PARENT_DIR}?
# or is there a better way to get `foo`?

The real use case is that originally foo was extracted via ${CMAKE_PROJECT_NAME}, but recently there’s a need to make the repo submodule compatible. Once this repo is being used as a submodule, ${CMAKE_PROJECT_NAME} won’t be equivalent to foo anymore. Additionally, bar is a submodule of foo, so we aren’t allowed to hard code foo into bar/CMakeLists.txt because that would break other repos that are using bar as a submodule.

Is there a way to extract the project name of a CMakeLists.txt from a parent directory?

Edit: I am looking for a solution that will make the below scenario work. Meaning foo is submoduled by another project. e.g.

baz
├───CMakeLists.txt
├───foo
│   ├───CMakeLists.txt
│   ├───bar
│        ├───CMakeLists.txt

>Solution :

Yes, the project name of the immediate parent.

This is not so hard. The project() command always sets the PROJECT_NAME variable when it is called. So the value of that variable just before you call project() is the name of the immediate parent.

There’s nothing standard for this, but it’s trivial to implement:

cmake_minimum_required(VERSION 3.23)

set(PARENT_PROJECT_NAME "${PROJECT_NAME}")
project(bar)

if (PARENT_PROJECT_NAME)
  message(STATUS "Found parent: ${PARENT_PROJECT_NAME}")
else ()
  message(STATUS "No parent!")
endif ()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading