Reputation: 313
I have added a subdirectory in CMake
by using add_subdirectory
. How can I access a variable from the scope of that subdirectory without explicitly setting the variable by using set
in combination with PARENT_SCOPE
?
set(BOX2D_BUILD_STATIC 1)
set(BOX2D_BUILD_EXAMPLES 0)
set(BOX2D_INSTALL_BY_DEFAULT 0)
add_subdirectory(Box2D_v2.2.1)
message(STATUS "Using Box2D version ${BOX2D_VERSION}")
# how to get ${BOX2D_VERSION} variable without modifying CMakeLists.txt in Box2D_v2.2.1?
Is this possible?
Upvotes: 6
Views: 5030
Reputation: 78330
While @Angew's answer is correct, there aren't many things that are really impossible with CMake :-)
If you have a line like
set(BOX2D_VERSION 2.2.1)
in Box2D_v2.2.1/CMakeLists.txt, then you can retrieve the version in the parent scope by doing something like:
file(STRINGS Box2D_v2.2.1/CMakeLists.txt VersionSetter
REGEX "^[ ]*set\\(BOX2D_VERSION")
string(REGEX REPLACE "(^[ ]*set\\(BOX2D_VERSION[ ]*)([^\\)]*)\\)" "\\2"
BOX2D_VERSION ${VersionSetter})
This is a bit fragile; it doesn't accommodate for extra spaces in the set
command for example, or cater for the value being set twice. You could cater for these possibilities too, but if you know the format of the set
command and it's unlikely to change, then this is a reasonable workaround.
Upvotes: 3
Reputation: 171127
If the variable is a plain variable (as opposed to a cache variable), there is no way to access it from the parent scope.
Cache variables (those set with set(... CACHE ...)
) can be accessed regardless of scope, as can global properties (set_property(GLOBAL ...)
).
Upvotes: 9