Buzz
Buzz

Reputation: 1412

Modify or set global variable from within Find<package>.cmake file

I'm striving to understand how to create / modify a global variable (whose prefix is not <PACKAGE>_) from within a Find<package>.cmake file, so that it can be shared among different modules and reused by the global CMakeLists.txt.

Let's say I have a FindMyModule.cmake file:

set (MyModule_include_dirs "...")  # <-- This is visible from CMakeLists.txt caller
set (LIBS_INCLUDE_DIRS "${LIBS_INCLUDE_DIRS} ${MyModule_include_dirs}") <-- This is not

In CMakeLists.txt

find_package(MyModule)
message("My Module include dirs: "${MyModule_include_dirs}) # <-- Prints "My Module include dirs: ..."
message("Libs include dirs: " ${LIBS_INCLUDE_DIRS}) # <-- Prints "Libs include dirs: "

Googling and so-ing around, I've tried CACHE, INTERNAL and PARENT_SCOPE but no successful result so far.

Upvotes: 0

Views: 667

Answers (1)

Milan Š.
Milan Š.

Reputation: 1638

I really don't understand why would you want to change a global variable from within a findXYZ.cmake script, as you are tightly coupling other scripts to this script or visa versa.

If I recall correctly, as long as you set a variable as CACHE INTERNAL before you start processing anything it should be available at all time to the following CMake instructions. We could've fixed that easily if you'd provide a minimal reproducible example.

The other options that you have for "GLOBAL variables" is to use set_property() i.e.:

set_property(GLOBAL PROPERTY GLOBAL_LIBS_INCLUDE_DIR "${LIBS_INCLUDE_DIR} ${MyModule_include_dirs}")

And then everywhere else:

get_property(LIBS_INCLUDE_DIR GLOBAL PROPERTY GLOBAL_LIBS_INCLUDE_DIR)

To demonstrate that BOTH WORK:

CMakeLists.txt

cmake_minimum_required (VERSION 3.20)
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR})

project ("GlobalVariables")

set(CACHE_INTERNAL_VARIABLE "HELLO" CACHE INTERNAL "")
set_property(GLOBAL PROPERTY GLOBAL_PROPERTY_VARIABLE "HELLO ")

find_package(MODULE_VARIABLE MODULE)

get_property(GLOBAL_PROPERTY_VARIABLE GLOBAL PROPERTY GLOBAL_PROPERTY_VARIABLE)
message(STATUS ${GLOBAL_PROPERTY_VARIABLE})
message(STATUS ${CACHE_INTERNAL_VARIABLE})

findMODULE_VARIABLE.cmake

set(CACHE_INTERNAL_VARIABLE "${CACHE_INTERNAL_VARIABLE} WORLD" CACHE INTERNAL "")
get_property(TEMP GLOBAL PROPERTY GLOBAL_PROPERTY_VARIABLE)
set_property(GLOBAL PROPERTY GLOBAL_PROPERTY_VARIABLE "${TEMP} WORLD")

Both variables output the same:

-- HELLO WORLD
-- HELLO WORLD

Upvotes: 0

Related Questions