[CMake] FOREACH loop control variable scope bug

Brad King brad.king at kitware.com
Wed Jun 22 13:21:58 EDT 2005


Bradley Lowekamp wrote:
> # top level CMakeLists.txt
> SET(var "this is var")
> FOREACH(LCV one)
>     MESSAGE("var: ${var} LCV: ${LCV}")
>     ADD_SUBDIRECTORY(foo)
> ENDFOREACH(LCV one two three)
> 
> # foo dir CMakeLists.txt
> MESSAGE("In Directory var: ${var} LCV: ${LCV}")
> 
> This produces the following output:
> 
> var: this is var LCV: one
> In Directory var: this is var LCV:
> 
> I expected LCV to be defined in the subdirectory just like any other 
> variable would have been. I realize this is can only happen with the new 
> immediate execution of the ADD_SUBDIRECTORY command. It appear that 
> there is some scoping issues with this variable.

The FOREACH "control variable" is not really a variable.  It is never 
actually set and has no scope.  The arguments of the commands inside the 
loop just have the text "${LCV}" replaced with each iteration's value. 
If you want to get its value from inside another command (like INCLUDE 
or ADD_SUBDIRECTORY) then you have to set it explicitly:

FOREACH(LCV one two three)
    SET(LCV "${LCV}")
    ADD_SUBDIRECTORY(foo)
ENDFOREACH(LCV)

-Brad


More information about the CMake mailing list