19

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?

Grant Limberg
  • 20,913
  • 11
  • 63
  • 84

2 Answers2

33

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.

bleater
  • 5,098
  • 50
  • 48
sakra
  • 62,199
  • 16
  • 168
  • 151
  • 5
    See also the "file(READ" command. You can read the whole file into a variable, and then do other string manipulations on it if necessary. – DLRdave Apr 21 '11 at 20:03
3

I don't know your OS, but I assune that you are using Windows or Linux.

if (UNIX)
  set (show_contents_prog cat)
elseif (WIN32)
  set (show_contents_prog type)
endif (WIN32)

execute_process(COMMAND ${show_contents_prog} input.txt OUTPUT_VARIABLE file_contents)

I think this may help.

beduin
  • 7,943
  • 3
  • 27
  • 24