How do I store basic information, like system name (Linux
), used compiler gcc
) or architecture (x86_64
), in a file that I include into my binary?
All the code for writing such a .in
file is already there, except that the relevant CMake variables are all empty, e.g. CMAKE_SYSTEM
or CMAKE_SYSTEM_PROCESSOR
:
set(NEWLINE "\\\\n")
file(WRITE ${CMAKE_BINARY_DIR}/update_buildflags.cmake "
file(WRITE \${DST} \"#define BUILDFLAGS \\\"
ARCH=\${CMAKE_SYSTEM}${NEWLINE}
COMP=\${CMAKE_SYSTEM_PROCESSOR}${NEWLINE}
BUILD=\${CMAKE_BUILD_TYPE}${NEWLINE}\\\"\n\")")
add_custom_target(update_buildflags COMMAND ${CMAKE_COMMAND}
-DDST=${PROJECT_SOURCE_DIR}/src/buildflags.c
-P ${CMAKE_BINARY_DIR}/update_buildflags.cmake)
This custom target is then added as dependency for the main binary and the resulting file src/buildflags.c
looks like this:
#define BUILDFLAGS " ARCH=\n COMP=\n BUILD=\n"
Why are the used CMake variables empty although printing them with message()
shows the correct information?
CMAKE_SYSTEM: Linux-4.4.0-92-generic
You can use an template file to make it more readable.
Example src/autocode/buildflags.h.in:
In your CMakeLists.txt
In your code
You need to remove the '\' before the $ when accessing CMAKE_... variables. Works like a charm afterwards.