[CMake] Question about variables, cache, and scope

Glenn Coombs glenn.coombs at gmail.com
Mon Oct 10 15:01:24 EDT 2011


Calling a function pushs a new variable scope.  All variables visible in the
callers scope are copied into the new scope but changes by default only
affect the callee scope.  You could try using the PARENT_SCOPE option to the
set command but I'm not sure that will achieve what you want as it only gets
you to the next scope whereas you really want a global variable.

You can use properties instead of variables as those are explicitly scoped.
So something like this:

set_property(GLOBAL PROPERTY project_count "0")

function( define_project ... )
   get_property(old_count GLOBAL PROPERTY project_count)
   math( EXPR new_count "${old_count}+1" )
   set_property(GLOBAL PROPERTY project_count "${new_count}"
endfunction()

will probably work.

--
Glenn


On 10 October 2011 17:11, Robert Dailey <rcdailey at gmail.com> wrote:

> I have a function that I define in my top-most CMakeLists.txt file (on
> Windows using CMake version 2.8.6) called define_project() that calls
> add_executable, sets up compile defintions, etc etc.
>
> For each time define_project() is called *anywhere* in the directory
> hierarchy, I need to increment a global "project_count" variable to keep
> track of how many projects were created and print that at the very end of
> the root CMakeLists.txt file.
>
> So far my attempts at this have been unsuccessful. I tried creating a cache
> variable in the root script:
>
> set( project_count 0 CACHE INTERNAL "" )
>
> Then inside of my function, I do this:
>
> function( define_project ... )
>    math( EXPR count "${project_count}+1" )
>    set( project_count ${count} )
> endfunction()
>
> However, 'project_count' is always 0 each time that the function is
> executed.
>
> How can I make this work?
>
> ---------
> Robert Dailey
>
> --
> Powered by www.kitware.com
>
> Visit other Kitware open-source projects at
> http://www.kitware.com/opensource/opensource.html
>
> Please keep messages on-topic and check the CMake FAQ at:
> http://www.cmake.org/Wiki/CMake_FAQ
>
> Follow this link to subscribe/unsubscribe:
> http://www.cmake.org/mailman/listinfo/cmake
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.cmake.org/pipermail/cmake/attachments/20111010/1a29a77b/attachment.htm>


More information about the CMake mailing list