Variable <PROJECT-NAME>_VERSION has a local scope. Thus a version variable, defined by a subproject, is not visible by a main project.
Assuming a subproject's CMakeLists.txt
performs project()
call like
project(<project-name> VERSION <version-string> ...)
version string can be easily extracted with regular expressions:
# subproject_version(<subproject-name> <result-variable>)
#
# Extract version of a sub-project, which was previously included with add_subdirectory().
function(subproject_version subproject_name VERSION_VAR)
# Read CMakeLists.txt for subproject and extract project() call(s) from it.
file(STRINGS "${${subproject_name}_SOURCE_DIR}/CMakeLists.txt" project_calls REGEX "[ \t]*project\\(")
# For every project() call try to extract its VERSION option
foreach(project_call ${project_calls})
string(REGEX MATCH "VERSION[ ]+([^ )]+)" version_param "${project_call}")
if(version_param)
set(version_value "${CMAKE_MATCH_1}")
endif()
endforeach()
if(version_value)
set(${VERSION_VAR} "${version_value}" PARENT_SCOPE)
else()
message("WARNING: Cannot extract version for subproject '${subproject_name}'")
endif()
endfunction(subproject_version)
# The function's usage:
subproject_version(gtest gtest_version)
message("VERSION for gtest: ${gtest_version}")
Implementation above uses variable <PROJECT-NAME>_SOURCE_DIR, which contains source directory of the subproject. Unlike to <PROJECT-NAME>_VERSION
variable, variable with source directory has global visibility (it is CACHED, actually), thus it can be used outside of the subproject.