23

I have a file version.txt

VERSION_MAJOR 1
VERSION_MINOR 1
VERSION_PATCH 3

I want to use cmake to add a definition for major, minor and patch.

I've tries using

file(STRING "version.txt" myvar)

but this just puts the whole file in myvar.

How do I get the numbers?

Maggick
  • 763
  • 2
  • 10
  • 26
  • 1
    Have you tried using a [regex](https://cmake.org/cmake/help/latest/command/string.html#regex-match)? – Florian Nov 02 '17 at 07:47
  • Possible duplicate of [CMake: Read build number from file to set a variable](https://stackoverflow.com/questions/5737433/cmake-read-build-number-from-file-to-set-a-variable) – Cinder Biscuits Nov 02 '17 at 14:14

1 Answers1

43

Your use of file is incorrect, you want to use READ in order to read the contents of the file into a variable.

file(READ "version.txt" ver)

Once you have the file's contents into a variable, you can then use REGEX MATCH with a capture group, and access the capture group using CMAKE_MATCH_N

REGEX MATCH:

Create a regular expression with a capture group which will capture the numbers following "VERSION_MAJOR":

string(REGEX MATCH "VERSION_MAJOR ([0-9]*)" _ ${ver})

Note that if the regex matches the input variable, the entire match will be stored in the output variable. However, we don't want the entire match (as that includes the string "VERSION_MAJOR"), so I've just used a variable name _ as the output variable, which, by convention, tells the user I am not interested in this variable

CMAKE_MATCH_N:

If the match is successful, then the capture groups are available in CMAKE_MATCH_N. In this instance there is only one capture group, so we want to use CMAKE_MATCH_1

set(ver_major ${CMAKE_MATCH_1})

At this point ver_major contains just the major version no.

You can then repeat this for the other version components.

Full example below:

cmake_minimum_required(VERSION 3.5)

file(READ "version.txt" ver)

string(REGEX MATCH "VERSION_MAJOR ([0-9]*)" _ ${ver})
set(ver_major ${CMAKE_MATCH_1})

string(REGEX MATCH "VERSION_MINOR ([0-9]*)" _ ${ver})
set(ver_minor ${CMAKE_MATCH_1})

string(REGEX MATCH "VERSION_PATCH ([0-9]*)" _ ${ver})
set(ver_patch ${CMAKE_MATCH_1})

message("version: ${ver_major}.${ver_minor}.${ver_patch}")

Output:

$ cmake .
version: 1.1.3
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp

For production code you would obviously want to make the cmake script more robust by checking whether the match was successful, and emitting an error if not.

starball
  • 20,030
  • 7
  • 43
  • 238
Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213
  • That is super helpful. I was trying to do the regex in the same line as the file that didn't work. What I found to also work was to turn it all into a list then index into 1, 3, and 5 – Maggick Nov 02 '17 at 23:40