How to determine when set(var ... PARENT_SCOPE) will work?

According to CMake Variable documentation you have Directory, Function, and cache scope. Using include() doesn’t create a new scope it is supposed to keep the current directory scope. add_subdirectory() is supposed to add an new Directory level.

So in a function PARENT_SCOPE should always work.

That leaves tracking if the current directory is the same as the top level directory. So if CMAKE_CURRENT_SOURCE_DIR is equal to CMAKE_SOURCE_DIR then there is no parent.

From the documentation of include:
Loads and runs CMake code from the file given. Variable reads and writes access the scope of the caller (dynamic scoping).

I’ve checked that CMAKE_CURRENT_SOURCE_DIR keeps the correct directory name in files that were included using the include() command as expected, the variable CMAKE_CURRENT_LIST_DIR is updated to track the directory of the included file.

But if this item could be included in both a function or a normal directory then you need to sort out if you are running in the context of a function. CMAKE_CURRENT_FUNCTION may be helpful in that case.

1 Like