Reputation: 11773
How do I share variables between different CMake files, and I show the following examples to illustrate my question:
cmake_minimum_required(VERSION 2.6)
project(test)
set(Var3 "Global variable")
add_subdirectory(${test_SOURCE_DIR}/exe)
add_subdirectory(${test_SOURCE_DIR}/dll)
set(Var1 "this is variable 1")
set(Var1 ${Var1} " added to varible 1")
message(STATUS ${Var1})
set(Var2 "this is variable 2")
message(STATUS ${Var2})
message(STATUS ${Var1})
message(STATUS ${Var3})
In this example, Var3 can be seen in the CMake files of exe
and dll
as it is defined in Main
. However, Var1, which is defined in exe
, will not be observed in dll
. I was just curious: is there a way to make Var1 defined in exe
observable in dll
?
Upvotes: 30
Views: 23053
Reputation: 5980
In my case I was applying a list(TRANSFORM)
on the variable, and these modifications were not reflected at global scope - apparently the list
command only in-place-modifies the local variable, and not the global one - I used an intermediary variable as a workaround:
set(MOC_HEADERS
application.hxx
command.hxx
menubar.hxx
uiloader.hxx
)
list(TRANSFORM MOC_HEADERS PREPEND "${CMAKE_CURRENT_LIST_DIR}/")
set(EASYQT_MOC_HEADERS ${MOC_HEADERS} CACHE INTERNAL "")
Upvotes: 0
Reputation: 20326
Beside what Tadeusz correctly said, you can make a variable visible at any level (not just one up!) by using
set(Var1 "This is variable 1" CACHE INTERNAL "")
The variable will be available for all the CMake instructions that follow that instruction, so for example it won't be available for a sister directory that is added before the directory where this variable is defined.
Upvotes: 33
Reputation: 8363
The scopes of variable visibility form a tree. The CMakeFiles.txt files added with add_subdirectory
have access to the variables defined in themselves, and in the parent scope (the toplevel global scope in your example).
You can export a variable one level up using:
set(Var1 "This is variable 1" PARENT_SCOPE)
Upvotes: 19