How to detect if current scope has a parent in CMake?
Asked Answered
J

3

27

Is there any way to detect if the current scope has a parent?

I have a project that can either be a standalone project or a sub-project of another. To allow the sub project case, I use the PARENT_SCOPE flag to set() to push things up to the parent. However, when build as a standalone project I get a "current scope has no parent" warning. I would like to avoid that error by detecting if there is a parent and enclosing the set() calls in an if statement. Or is there another way to set a variable at parent scope only if there is a parent?

Jenniejennifer answered 8/8, 2014 at 9:2 Comment(0)
K
45

I think the most robust approach is to use the PARENT_DIRECTORY directory property.

This will yield the correct answer regardless of whether it's called before or after the project command, and regardless of whether the parent and child both have the same project name.

get_directory_property(hasParent PARENT_DIRECTORY)
if(hasParent)
  message(STATUS "Has a parent scope.")
else()
  message(STATUS "Doesn't have a parent scope.")
endif()
Kassel answered 9/8, 2014 at 11:12 Comment(0)
L
13

CMake version 3.21 added the PROJECT_IS_TOP_LEVEL global variable for this:

A boolean variable indicating whether the most recently called project() command in the current scope or above was in the top level CMakeLists.txt file.

project(my_project)
[...]

if(PROJECT_IS_TOP_LEVEL)
  message(STATUS "Is a top-level project.")
endif()
Lamrouex answered 17/8, 2021 at 15:50 Comment(0)
F
3

Expanding a bit on @ruslo idea I would not take the PROJECT_SOURCE_DIR but the CMAKE_PROJECT_NAME variable (contains the name of the first defined project) and the PROJECT_NAME (contains the name of the current project), so you could do something like this in the CMakeLists.txt of the Subproject:

project(bar)

if(${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME})
 #do stuff
else()
 #do other stuff
endif()
Firstling answered 8/8, 2014 at 20:51 Comment(2)
You can't nest the if(... STREQUAL ...) inside the set command.Kassel
Good point, I did not think of that and didn't test it. I'll move the test directly in the if. Btw good call with the PARENT_DIRECTORY property. I did not know that exists.Firstling

© 2022 - 2024 — McMap. All rights reserved.