variable scoping confusion..

Scopes in CMake are…complicated.

First, there are two main classes of variables:

  • cached
  • local

Local variables are “normal” in that they disappear when a scope ends (functions, directories). Normal set and things like list() and string() operate on local variables.

Cache variables are global with the following caveats:

  • any defined local variable of the same name will shadow the cache variable
  • set(CACHE) will not change an already-cached variable except when either:
    • the specified type is INTERNAL; or
    • the FORCE argument is specified

You can only set local variables in your current scope or in the immediate parent scope. To pass it through multiple functions, all of them will need to “fire brigade” the value up the stack with PARENT_SCOPE calls.

If you need truly global variables but not cached between configure runs, I recommend using custom global properties instead:

set_property(GLOBAL PROPERTY mypropname value)
get_property(localvar GLOBAL PROPERTY mypropname)

There’s not really a debugger as such. cmake --trace-expand is useful though.