[CMake] Functions inherit parent variables?
Johannes Zarl
johannes.zarl at jku.at
Mon Mar 5 04:43:51 EST 2012
On Saturday 03 March 2012, 02:29:05, Robert Dailey wrote:
> Well you're really comparing apples to oranges. C++ nested scoping rules
> really have nothing to do with two separate functions sharing scoped
> variables. It doesn't even really serve as a good analogy, so I can't be
> 100% certain what you were trying to tell me ;-)
>
> However I appreciate your response. I really just wanted to make sure this
> isn't a bug, because the way the called function inherits the calling
> function's local variables is an unusual behavior for a language, at least
> in my experience. So I had to think twice about it ;)
As Michael said: This behaviour is not at all unusual for scripting languages,
but there is not really a One True Way: In Tcl you have to import variables
explicitly, in bourne shell you overwrite values in the parent scope, ...
It's just a property of the language that you have to know about.
So in the CMake language you should be aware that the parent scope is visible
inside a function, but the function does not affect the parent scope unless
explicitly stated:
function( test1 )
set( var_a "var_a inner1" )
message( "test1(): var_a: ${var_a}" )
endfunction()
function( test2 )
set( var_a "var_a inner2" PARENT_SCOPE )
message( "test2(): var_a: ${var_a}" )
endfunction()
set( var_a "var_a outer" )
test1()
message( "var_a: ${var_a}" )
test2()
message( "var_a: ${var_a}" )
--- Output:
test1(): var_a: var_a inner1
var_a: var_a outer
test2(): var_a: var_a outer
var_a: var_a inner2
Disclaimer: Actually, this was surprising to me. I was thinking that
PARENT_SCOPE sets the value in the current scope plus the parent scope, not in
the parent scope only. I guess this could be stated in the documentation more
clearly...
Johannes
More information about the CMake
mailing list