1

Lets say I have a file info.cmake which has:

set(a 1)
set(b 2)
set(c 3)

Now a project can load it via include :

include(../info.cmake)

to access the value associated to a but that would pollute the environment with values for b and c. Is there any way of reading only the value of a potentially thorugh get_property()?

Maths noob
  • 1,684
  • 20
  • 42

2 Answers2

1

You could add a local variable scope with a wrapper function

function(my_info_wrapper_function)
    include(../info.cmake)
    set(a "${a}" PARENT_SCOPE)
endfunction()

my_info_wrapper_function()

But this would only encapsulate local variables. Your CMakeLists.txt file will still be "polluted" if info.cmake does e.g. change cached variables or add any targets.

References

Community
  • 1
  • 1
Florian
  • 39,996
  • 9
  • 133
  • 149
0

As Florian mentioned, you will have to resort to using a function with its own scope. Here is a more general version of what was suggested which can be given the path to the source file and the variable to be looked up:

function(lookup value)
    set(options
            ""
            )
    set(oneValueArgs
            SOURCE
            VARIABLE
            )
    set(multiValueArgs
            ""
            )
    cmake_parse_arguments(LOOKUP "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
    if(EXISTS "${LOOKUP_SOURCE}")
        include("${LOOKUP_SOURCE}")
        set(key     ${LOOKUP_VARIABLE})
        if(NOT ${key})
            message(SEND_WARNING "No value was set for ${LOOKUP_VARIABLE} in the source file: ${LOOKUP_SOURCE}")
        endif(${key})
        set(${value} ${${key}} PARENT_SCOPE)
    else()
        message(SEND_ERROR "The source file was not found at ${LOOKUP_SOURCE}")
    endif()
endfunction()

This is how you can use it:

lookup(val
        SOURCE       ../info.cmake
        VARIABLE     a)
message(SEND_ERROR ${val}) #Will Print 1
  • 2
    Just a suggestion: replacing `if(NOT ${key})` with `if(DEFINED ${key})` would not send a warning if the value is `0`, `OFF`, `NO`, `FALSE`, `N`, `IGNORE` or `NOTFOUND`. – Florian Apr 20 '16 at 10:26