[CMake] Function variable name question

Matthew Woehlke mw_triad at users.sourceforge.net
Tue Jan 27 13:10:55 EST 2009


James Bigler wrote:
> On Tue, Jan 27, 2009 at 10:46 AM, Matthew Woehlke <
> mw_triad at users.sourceforge.net> wrote:
> 
>> James Bigler wrote:
>>
>>> I have the following code in a script:
>>>
>>> function(set_var var)
>>>  message("var = ${var}")
>>>  message("${var} = ${${var}}")
>>>  set(${var} "new_val")
>>>  message("${var} = ${${var}}\n")
>>> endfunction()
>>>
>>> set(myvar 10)
>>> set_var(myvar)
>>>
>>> # Empty variable
>>> set_var(myvar2)
>>>
>>> set_var(var)
>>>
>>> # Set variable
>>> set(var 11)
>>> set_var(var)
>>>
>>> When I run it I get the following output:
>>>
>>> var = myvar
>>> myvar = 10
>>> myvar = new_val
>>>
>>> var = myvar2
>>> myvar2 =
>>> myvar2 = new_val
>>>
>>> var = var
>>> var = var
>>> new_val =
>>>
>>> var = var
>>> var = var
>>> new_val =
>>>
>>> I get expected output when the name of the variable I pass in isn't the
>>> same
>>> as the one used in the function parameter list.
>>>
>>> Is this the desired behavior of the language?  I would argue that it
>>> isn't,
>>> because you get different behavior based on the name of the variable
>>> passed
>>> in.
>>
>> Um... and how would you claim it is supposed to work? You've got a classic
>> case of variable shadowing here. If you think about it, CMake is doing
>> exactly what you told it to do.
> 
> Grrrr....I see that now.
> 
> ${var} evaluates to var and there's no way to know if that's the function's
> var or the global scope's var.

Right :-).

> I know you could probably mangle the parameter names to decrease the
> probability of collisions, but is there any assured method to avoid
> collisions?

I doubt there is a technical way to do it (it would be complicated, with 
questionable value compared to the cost). Enforcing a good naming scheme 
is probably your best bet; you could, for example, prefix parameter 
names with the name of the function.

-- 
Matthew
Please do not quote my e-mail address unobfuscated in message bodies.
-- 
Anyone who is capable of getting themselves made President should on no 
account be allowed to do the job. -- Douglas Adams



More information about the CMake mailing list