Does CMake's set(... PARENT_SCOPE) only set a variable value one scope upward?

600 Views Asked by At

I am new to cmake. I am using cmake_minimum_required(VERSION 3.20) Following is the structure of my code:

Root
    |CMakeLists.txt
    |Subdirectory
         |CMakeLists.txt
         |Sub-subdirectory
               |CMakeLists.txt

I store some .cpp files in varname in the CMakeLists.txt file for Sub-subdirectory: set(varname FILES PARENT_SCOPE). I would like varname to be accessible in the Root CMakeLists.txt file. However, the option PARENT_SCOPE only makes them accessible one directory up, in Sub-directory, but not in Root. Is there a way to make the files accessible in Root?

One alternative I could find is using file(GLOB ...) however GLOB is not recommended by cmake developers so I want to avoid using it.

1

There are 1 best solutions below

0
starball On

Yes, PARENT_SCOPE for the set command only sets the the variable value in the parent scope of the scope it is used in. If you want to go up multiple parent scopes, each scope has to copy the variable value up until it has reached the desired scope. You could use a global property (set_property(GLOBAL)) to avoid that if if so wish: set the global property in a deeply nested scope, then copy out the global property into a CMake variable with get_property(GLOBAL). Whether you think such an approach is acceptable or not is up to you and the details of your project. Or, if possible, just set the variable at the scope you want its value to be set at instead of in a deeper scope.

Note that if the end purpose of this variable that stores a list of filenames is only to add it to the list of source files for a target, then I see this as an XY problem. You can be using target_sources. I actually find it convenient to combine usage of target_sources for source files in subdirectories with add_subdirectory because relative paths in CMake-subdirectories are taken as relative to the path of the subdirectory.