How to get the version of a program in CMake

Problematic

When interacting with other programs through the cmake language, you may have encountered some problem when updating those programs, such has a feature not available anymore, or a modification which broke the cmake script. In such case, being able to know which version the program installed on the machine can be very helpful ! 😄

Solution

Before trying to get the version of a program installed on a machine, the first thing we have to do is to check if the program is indeed installed on the machine !

Is the program installed

In CMake, such a function could look like that:

set(PROGRAM_NAME my_program)
set(PROGRAM_HINT_PATHS /some/paths/to/look/in)
function(${PROGRAM_NAME}_is_installed output_var)
unset(${PROGRAM_NAME}_EXECUTABLE CACHE)
find_program(${PROGRAM_NAME}_EXECUTABLE
NAMES ${PROGRAM_NAME}
HINTS ${PROGRAM_HINT_PATHS}
DOC "${PROGRAM_NAME} executable")
if(NOT ${PROGRAM_NAME}_EXECUTABLE)
set(${output_var} FALSE PARENT_SCOPE)
else()
set(${output_var} TRUE PARENT_SCOPE)
endif()
endfunction()

Let’s get the version of this program

Now that we know how to check if a program is installed, we can create a function to get the version of a program.

set(PROGRAM_NAME my_program)function(${PROGRAM_NAME}_version output_var)
${PROGRAM_NAME}_is_installed(IS_${PROGRAM_NAME}_INSTALLED)
if(NOT ${IS_${PROGRAM_NAME}_INSTALLED})
message(FATAL_ERROR "${PROGRAM_NAME} must be installed on the
machine!")
endif()
# Runs the command to get the pluginval version
execute_process(COMMAND ${PROGRAM_NAME} --version
OUTPUT_VARIABLE ${PROGRAM_NAME}_VERSION_RAW_OUTPUT)
# Extracts the version from the output of the command run before
string(STRIP ${${PROGRAM_NAME}_VERSION_OUTPUT}
${PROGRAM_NAME}_VERSION_OUTPUT)
set(${output_var} ${${PROGRAM_NAME}_VERSION_OUTPUT} PARENT_SCOPE)
endfunction()
set(PROGRAM_NAME my_program)${PROGRAM_NAME}_version(${PROGRAM_NAME}_VERSION)message(STATUS "${PROGRAM_NAME} version detected :
${${PROGRAM_NAME}_VERSION}")

What’s next ?

In CMake, there is a function which does something similar to what we want, allynd this function is named cmake_minimum_required. This function sets the minimum required version of cmake for a project.

Interesting links

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store