Home > Software engineering >  CMake: how to embed build configuration (Debug, Release, MinSizeRel,...) into binary?
CMake: how to embed build configuration (Debug, Release, MinSizeRel,...) into binary?

Time:04-04

I'm using Cmake's configure_file() function to generate a header that I include into my project. This way, I can for example store into the resulting binary the git commit hash of the code beeing compiled.

Now I'm trying to make my program aware of the compilation configuration which has been used: Debug, Release, MinSizeRel or RelWithDebInfo.

The toolchain used is VisualStudio, therefore all configurations are generated by CMake at the same time. So for example, CMAKE_BUILD_TYPE is alays set to Release.

What is the common way to make the program built aware of the the build mode used ?

CodePudding user response:

You may create a file, containing build type-specific values, using file(GENERATE) command. This command expands generator expressions.

For example, the call

file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/build_$<CONFIG>
  CONTENT "Build type: $<CONFIG>")

at the end of configuration will create build_Debug file with content Build type: Debug, build_Release file with content Build type: Release and so on.

Resulted files could be used in custom commands:

add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/some_file_$<CONFIG> 
  DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/build_$<CONFIG>
  COMMAND do-something-with build_$<CONFIG>
)

Note, that file(GENERATE) doesn't expand variables. So if you want to combine in the resulted file both variables values and generator expressions, then you need to "pipe" configure_file with file(GENERATE).

my_file.in:

var: @MY_VAR@
build type: $<CONFIG>

CMakeLists.txt:

# Creates intermediate file with expanded variables.
configure_file(my_file.in my_file_intermediate @ONLY)
# Expands generator expressions in the intermediate file and creates "final" files
file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/my_file_$<CONFIG>
  INPUT ${CMAKE_CURRENT_BINARY_DIR}/my_file_intermediate)

CodePudding user response:

You can use CMake generator expressions with the add_compile_definitions command.

Like this: add_compile_definitions(CONFIG_TYPE="$<CONFIG>"). Then use the CONFIG_TYPE macro in your C code.

  • Related