MantisBT - CMake
View Issue Details
0013523CMakeCMakepublic2012-09-06 20:202013-03-04 08:38
szx 
 
normalminoralways
closedno change required 
Any
CMake 2.8.9 
 
0013523: Function defined in a subdiretory can't see its global variables when called from outside
Usually functions can read global variables that are set in the same directory. But this doesn't work when a function that is defined in a subdirectory is called from its parent directory.
1. Create CMakeLists.txt with the following text:

cmake_minimum_required(VERSION 2.8)
set(FOO "bar")
function(test)
    message("test(): FOO=${FOO}")
endfunction()
test()
add_subdirectory(sub)
sub_test()


2. Create a subdirectory called "sub" and another CMakeLists.txt in it:

set(SUB_FOO "sub_bar")
function(sub_test)
    message("sub_test(): SUB_FOO=${SUB_FOO}")
endfunction()

3. Run cmake against the root directory



Exptected output:

test(): FOO=bar
sub_test(): SUB_FOO=sub_bar

Actual result:

test(): FOO=bar
sub_test(): SUB_FOO=
No tags attached.
zip test.zip (805) 2012-09-06 20:20
https://public.kitware.com/Bug/file/4458/test.zip
Issue History
2012-09-06 20:20szxNew Issue
2012-09-06 20:20szxFile Added: test.zip
2012-09-07 04:07Rolf Eike BeerNote Added: 0030952
2012-09-07 04:07Rolf Eike BeerStatusnew => resolved
2012-09-07 04:07Rolf Eike BeerResolutionopen => no change required
2013-03-04 08:38Robert MaynardNote Added: 0032441
2013-03-04 08:38Robert MaynardStatusresolved => closed

Notes
(0030952)
Rolf Eike Beer   
2012-09-07 04:07   
This behaves exactly as expected. When you call sub_test you are not in the subdirectory anymore, so SUB_FOO is not set anymore. This variable exists only in the scope of the subdirectory, which you already left so the variable is destroyed.

If you want SUB_FOO to be "sort of" global you can append PARENT_SCOPE to the set() in the subdirectory, so the variable will exist one scope (i.e. directory or function) level upwards, too.
(0032441)
Robert Maynard   
2013-03-04 08:38   
Closing resolved issues that have not been updated in more than 4 months.