Is there a native way in CMake to write an int to a file as bytes?
E.g.
file(SIZE generated_file.txt file_size) # file_size == 465435
file(WRITE output.txt "${file_size}"
Where I would like ${file_size}
written as a fixed number of bytes (E.g. 4) \x00\x07\x1a\x1b
vs 465435
CMake doesn't have integer types. It just has strings. If you want to encode a non-ASCII number literal as a CMake string, the docs for escape sequences in CMake strings is here: https://cmake.org/cmake/help/latest/manual/cmake-language.7.html#escape-sequences. There seems to be no way to write binary/hex literals other than to actually put those characters in the string (and escape them if necessary- Ex. \"
).
Another approach would be to invoke a program that converts the ASCII decimal string to the integer value and writes it to the file, or outputs the integer to the standard output stream and then use the mechanism of whatever CMake command you use to invoke that program to get the standard output as a CMake string and then call file(WRITE ...)
. To do that at configure-time, see execute_process
. To do it at build-time, see add_custom_command
or add_custom_target
.