Set a variable in current scope and PARENT_SCOPE?

4.7k Views Asked by At

If I do:

set(SourceDir ${CMAKE_CURRENT_SOURCE_DIR} PARENT_SCOPE)
message("SourceDir: " ${SourceDir})

The message says that SourceDir is empty. Presumably it is being set in the parent scope only. Is there a way to set the variable in the current scope AND the parent scope? So that I don't have to do:

set(SourceDir ${CMAKE_CURRENT_SOURCE_DIR} PARENT_SCOPE)
set(SourceDir ${CMAKE_CURRENT_SOURCE_DIR})
message("SourceDir: " ${SourceDir})
2

There are 2 best solutions below

0
Doncho Gunchev On

I think you can not. The documentation says:

Each new directory or function creates a new scope.

If I understand it correctly when your SET gets executed, its scope is already created by copying the parent scope. So no matter what you do to the original (PARENT_SCOPE) your local scope won't change.

You'd better ask the question on CMake's user list to verify that they don't do fallback to parent when a variable is not defined in the local scope. If they do however, this is a bug.

1
Sharath On

When you set it for PARENT_SCOPE, it doesn't do it for current scope somehow. But a two step process works. The first line sets it locally, the second line exports it to the parent scope.

set (LIB_VER 6)
set (LIB_VER ${LIB_VER} PARENT_SCOPE)