In CMake, why is a variable set in a subdirectory invisible to the parent after add_subdirectory, and what does PARENT_SCOPE change?
answer
- each directory gets its own scope
- the child starts with a copy
- PARENT_SCOPE writes one level up
- the current scope keeps its old value
- cache entries are not scoped
basics
~20 sadd_subdirectory gives the child a new directory scope initialised with a copy of the parent's variables, so the child's set() calls stay local. set(NAME value PARENT_SCOPE) writes the parent's binding instead, leaving the child's own copy unchanged.
solid answer
~40 sEach directory has its own **variable scope**. When `add_subdirectory(audio)` runs, CMake copies every binding the parent has at that moment into the child's new scope; a `set()` in `audio/CMakeLists.txt` then binds only in that copy and is gone when the child finishes. `set(NAME value PARENT_SCOPE)` writes the binding into the **parent** scope instead, and, the part people miss, does not change the value in the current scope. Directories added later copy the parent's updated value, so they see it too. Functions follow the same rule for their caller, and since CMake 3.25 `block(PROPAGATE ...)` does the same job for a block. Cache entries are not scoped at all, but using the cache to pass values around leaves them persisting in `CMakeCache.txt`.
code
cmake · 14 lines# CMakeLists.txt (top level)
set(ENGINE_FEATURES "core")
add_subdirectory(audio)
message(STATUS "top after audio: ENGINE_FEATURES=${ENGINE_FEATURES} AUDIO_LOCAL=${AUDIO_LOCAL}")
add_subdirectory(net)
# audio/CMakeLists.txt
message(STATUS "audio sees: ENGINE_FEATURES=${ENGINE_FEATURES}")
set(AUDIO_LOCAL "yes")
set(ENGINE_FEATURES "${ENGINE_FEATURES};audio" PARENT_SCOPE)
message(STATUS "audio after PARENT_SCOPE: ENGINE_FEATURES=${ENGINE_FEATURES}")
# net/CMakeLists.txt
message(STATUS "net sees: ENGINE_FEATURES=${ENGINE_FEATURES} AUDIO_LOCAL=${AUDIO_LOCAL}")go deeper
Recall that every directory added with add_subdirectory has its own variable scope and that set() there stays local.
Explain the copy-on-entry rule, why PARENT_SCOPE leaves the current value unchanged, and why later siblings see a propagated value.
Spot code that reads a variable right after setting it with PARENT_SCOPE, and replace variable plumbing with target usage requirements.
Prefer target-centric structure so directories exchange targets, not variables, and keep cache entries for genuine user settings.
## Scopes in the CMake language CMake normal variables have **dynamic scope**: every `set()` or `unset()` creates a binding in the *current* scope, and a reference looks through the current scopes before falling back to the cache. Three things open a new scope: - **Directory scope**: every directory processed through `add_subdirectory()` gets one. - **Function scope**: every call of a command defined with `function()`. - **Block scope**: `block()` ... `endblock()`, added in CMake 3.25. The cache sits beside all of these: one global, persistent set of entries with no scoping. ## What add_subdirectory copies The `cmake-language(7)` manual says that before processing a directory's `CMakeLists.txt`, CMake **copies all variable bindings currently defined in the parent directory** to initialise the new scope. Three consequences follow: 1. The child sees everything the parent had set *before* the `add_subdirectory()` call, and nothing the parent sets afterwards. 2. A `set()` in the child changes only the child's copy; when the child finishes, the copy is discarded. 3. A later sibling directory receives a fresh copy of the parent, so it never sees the first child's local variables. ## PARENT_SCOPE `set(NAME value PARENT_SCOPE)` binds `NAME` in the scope above the current one: the parent directory, the calling function's scope, or the enclosing block. The `set` documentation is explicit that the previous state of the variable in the **current** scope stays the same: if it was undefined, it stays undefined; if it had a value, it keeps that value. `unset(NAME PARENT_SCOPE)` removes the parent's binding in the same way. A run with CMake 4.4.4 shows every rule at once: ```console -- audio sees: ENGINE_FEATURES=core -- audio after PARENT_SCOPE: ENGINE_FEATURES=core -- top after audio: ENGINE_FEATURES=core;audio AUDIO_LOCAL= -- net sees: ENGINE_FEATURES=core;audio AUDIO_LOCAL= ``` The child `audio` appended to `ENGINE_FEATURES` with `PARENT_SCOPE`, yet its own copy still read `core`. Its plain `set(AUDIO_LOCAL yes)` never reached the parent. The sibling `net`, added afterwards, copied the parent's updated list. | Command in the child | Child sees | Parent sees | Later siblings see | |---|---|---|---| | `set(X 1)` | `1` | old value | old value | | `set(X 1 PARENT_SCOPE)` | old value | `1` | `1` | | both lines | `1` | `1` | `1` | ## include() is not add_subdirectory() `include(cmake/Warnings.cmake)` loads and runs the file **in the current scope**: no copy is made, so every plain `set()` in the included file is visible to the includer afterwards, and every variable the includer had is visible inside it. That is why helper modules are loaded with `include()`, and why a module that sets temporaries without a function or `block()` pollutes the directory that includes it. `add_subdirectory()` is the command that creates a new directory scope. ## Common mistakes - **Expecting PARENT_SCOPE to update the current scope too.** Code that sets with `PARENT_SCOPE` and then reads the variable locally sees the old value. Set it twice, once locally and once with `PARENT_SCOPE`, when both need it. - **Passing values up through the cache.** A cache entry is visible everywhere, so it looks like a fix. But it persists in `CMakeCache.txt`, appears in `cmake-gui` as a user setting, and a non-`FORCE` set will not update it on the next run. - **Deep nesting.** `PARENT_SCOPE` goes up exactly one level; a value produced three directories down must be forwarded at every level. - **Using variables where a target would do.** Lists of sources, include directories or flags are usually better attached to a target with `target_sources()`, `target_include_directories()` or `target_compile_options()`. Targets are global, and their usage requirements propagate without any scope plumbing. ## block() for local work `block()` (CMake 3.25) opens a variable scope inside a single file, so temporaries can be used without leaking into the rest of the directory. `block(PROPAGATE result)` copies the named variables to the enclosing scope when the block ends, which reads more clearly than `PARENT_SCOPE` sprinkled through the body. A block also opens a policy scope unless `SCOPE_FOR` restricts it.
- If the parent sets a variable after calling add_subdirectory, does the child see it?No. The child's scope is initialised with a copy of the parent's bindings at the moment `add_subdirectory()` runs, and the child's `CMakeLists.txt` is processed during that call. Anything the parent sets later is outside that snapshot. Set configuration values before the `add_subdirectory()` calls that need them.
- When is block(PROPAGATE ...) better than PARENT_SCOPE?Inside one file, `block()` (CMake 3.25) opens a scope for temporaries without needing a function, and `PROPAGATE` lists in one place which results leave it. With `PARENT_SCOPE` you must remember that the current scope keeps its old value; with `block(PROPAGATE x)` the value set inside is the one copied out when the block ends.
- Expects set() in a subdirectory to change the parent's variable
- Thinks PARENT_SCOPE also updates the value in the current scope
- Believes PARENT_SCOPE reaches the top-level directory from any depth
- Passes values upward through cache entries to dodge scoping
- Assumes a child sees variables the parent sets after add_subdirectory