CMake: Read build number from file to set a variable

Grant Limberg picture Grant Limberg · Apr 21, 2011 · Viewed 19k times · Source

I'm working on a project where the build number is stored in a file called 'BuildNumber.txt' at the root of the project. What I'd like to do is have CMake read the number from this file and set a variable that can be applied to a header file.

setup.h.in

#define build_number "@BUILD_NUMBER@";

Using configure_file, it's possible to replace placeholders in an .in file like above with a CMake variable. Is it possible to get CMake to read in the number from BuildNumber.txt into a variable?

Answer

sakra picture sakra · Apr 21, 2011

You can use the CMake command file (STRINGS ...) for that purpose. Assuming the build number is located in the file BuildNumber.txt in a single line, the following command will read it into the CMake variable BUILD_NUMBER:

file (STRINGS "BuildNumber.txt" BUILD_NUMBER)

Also see the file command reference.