CMake: Store build/system information in binary

2019-08-10 22:35发布

问题:

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

回答1:

You can use an template file to make it more readable.

  • Pro: Not necessary to write the whole file within cmake
  • Pro: Easy to edit
  • Contra: Additional file

Example src/autocode/buildflags.h.in:

#ifndef BUILD_FLAGS_H
#def BUILD_FLAGS_H  
#define ARCH ${CMAKE_SYSTEM}
#define COMP ${CMAKE_SYSTEM_PROCESSOR}
#define BUILD ${CMAKE_BUILD_TYPE} 
// Add more of your stuff here
#define APP_BUILD_WITH_CMAKE_VERSION "${CMAKE_VERSION}"
#define APP_BUILD_ON_PLATFORM "${CMAKE_SYSTEM}"
#endif // BUILD_FLAGS_H

In your CMakeLists.txt

configure_file(${CMAKE_CURRENT_SOURCE_DIR}/autocode/buildflags.h.in 
               ${CMAKE_BINARY_DIR}/buildflags.h)
include_directories(${CMAKE_BINARY_DIR})

In your code

#include "buildflags.h"


回答2:

You need to remove the '\' before the $ when accessing CMAKE_... variables. Works like a charm afterwards.



标签: cmake