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
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 ()