How it works

We used the following construct to read the version string from a file called VERSION:

if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/VERSION")  file(READ "${CMAKE_CURRENT_SOURCE_DIR}/VERSION" PROGRAM_VERSION)  string(STRIP "${PROGRAM_VERSION}" PROGRAM_VERSION)
else()  message(FATAL_ERROR "File ${CMAKE_CURRENT_SOURCE_DIR}/VERSION not found")endif()

Here, we first check that this file exists, and issue an error message if it does not. If it exists, we read its contents into a variable called PROGRAM_VERSION, which we strip of any trailing whitespace. Once the variable PROGRAM_VERSION is set, it can be used to configure version.hpp.in to generate generated/version.hpp, as follows:

configure_file(  version.hpp.in  generated/version.hpp @ONLY ...

Get CMake Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.