CMake: how to access a variable from a subdirectory without explicitly setting it to the parent area

I added a subdirectory to CMake using add_subdirectory . How can I access a variable from the scope of this subdirectory without setting the variable explicitly with 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 it possible?

+6
source share
2 answers

If the variable is a simple variable (as opposed to a cache variable), there is no way to access it from the parent scope.

Cache variables (those set using set(... CACHE ...) ) can be accessed regardless of scope, as well as global properties ( set_property(GLOBAL ...) ).

+7
source

Although @Angew's answer is correct, there are not many things in CMake that are really impossible :-)

If you have a string like

 set(BOX2D_VERSION 2.2.1) 

in Box2D_v2.2.1 / CMakeLists.txt, you can get the version in the parent area 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}) 

It is a little fragile; it is not suitable for extra spaces in the set command, for example, or for setting a value set twice. You can also use these features, but if you know the format of the set command, and that is unlikely to change, then this is a smart solution.

+3
source

All Articles