Kirill Daybov
Kirill Daybov

Reputation: 490

Generate preprocessor definitions based on CMAKE_CONFIGURATION_TYPES

I want to generate a Visual Studio project with two configurations using cmake. I want cmake to define different preprocessor symbols for these configurations.

I generate the project with the following command

cmake -B intermediate/cmake -G "Visual Studio 16 2019" -T v142 -DCMAKE_GENERATOR_PLATFORM=x64

In my CMakeLists.txt I define configurations:

if(CMAKE_CONFIGURATION_TYPES)
  set(CMAKE_CONFIGURATION_TYPES Debug Release)
endif()

Now, how do I define the preprocessor definitions per configuration? The quick search advises against using if(CMAKE_BUILD_TYPE STREQUAL "Release") because it doesn't work for multiconfiguration generators.

Upvotes: 1

Views: 1842

Answers (1)

Bitwize
Bitwize

Reputation: 11210

The conventional way to handle configuration-specific details in a multi-configuration generator is through the use of generator expressions.

Generator expressions allow you to specify symbols, values, flags, etc that will only be expanded at generation time based on the current state of the generator (such as the current build configuration).

For example, you can define custom pre-processor definitions with the -D flag with target_compile_definitions:

target_compile_definitions(MyTarget PRIVATE
  $<$<CONFIG:Debug>:DEBUG_ONLY=1>
  $<$<CONFIG:Release>:RELEASE_ONLY=2>
  FOO=3
)

(This example is for PRIVATE definitions. Replace this with PUBLIC or INTERFACE as needed.)

This adds -DDEBUG_ONLY=1 to MyTarget for Debug builds, -DRELEASE_ONLY=2 for Release builds, and -DFOO=3 for all builds.


Also see this relevant/similar question: Cmake: Specifiy config specific settings for multi-config cmake project

Upvotes: 1

Related Questions