Skip to content

Instantly share code, notes, and snippets.

@oliora
Last active June 17, 2023 05:59
Show Gist options
  • Save oliora/4961727299ed67337aba to your computer and use it in GitHub Desktop.
Save oliora/4961727299ed67337aba to your computer and use it in GitHub Desktop.
Forward added/changed variables to the function's parent scope
# forward_variables usage example
include(forward_variables.cmake)
# After call to this function, all variables set by find_package will be forwarded to
# function caller scope (i.e. into parent scope).
function(find_boost_package)
start_track_variables()
set(bla_bla 1)
find_package(Boost 1.55 COMPONENTS system filesystem)
forward_changed_variables_to_parent_scope(bla_bla)
endfunction()
find_boost_package()
message(STATUS "${Boost_LIBRARIES}")
# Start to track variables for change or adding.
# Note that variables starting with underscore are ignored.
macro(start_track_variables)
get_cmake_property(_fnvtps_cache_vars CACHE_VARIABLES)
get_cmake_property(_fnvtps_old_vars VARIABLES)
foreach(_i ${_fnvtps_old_vars})
if (NOT "x${_i}" MATCHES "^x_.*$")
list(FIND _fnvtps_cache_vars ${_i} _fnvtps_is_in_cache)
if(${_fnvtps_is_in_cache} EQUAL -1)
set("_fnvtps_old${_i}" ${${_i}})
#message(STATUS "_fnvtps_old${_i} = ${_fnvtps_old${_i}}")
endif()
endif()
endforeach()
endmacro()
# forward_changed_variables_to_parent_scope([exclusions])
# Forwards variables that was added/changed since last call to start_track_variables() to the parent scope.
# Note that variables starting with underscore are ignored.
macro(forward_changed_variables_to_parent_scope)
get_cmake_property(_fnvtps_cache_vars CACHE_VARIABLES)
get_cmake_property(_fnvtps_vars VARIABLES)
set(_fnvtps_cache_vars ${_fnvtps_cache_vars} ${ARGN})
foreach(_i ${_fnvtps_vars})
if (NOT "x${_i}" MATCHES "^x_.*$")
list(FIND _fnvtps_cache_vars ${_i} _fnvtps_is_in_cache)
if (${_fnvtps_is_in_cache} EQUAL -1)
list(FIND _fnvtps_old_vars ${_i} _fnvtps_is_old)
if(${_fnvtps_is_old} EQUAL -1 OR NOT "${${_i}}" STREQUAL "${_fnvtps_old${_i}}")
set(${_i} ${${_i}} PARENT_SCOPE)
#message(STATUS "forwarded var ${_i}")
endif()
endif()
endif()
endforeach()
endmacro()
@devshgraphicsprogramming

what's the license for this script?

@oliora
Copy link
Author

oliora commented Oct 19, 2020

@devshgraphicsprogramming It’s public domain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment