Search code examples
visual-studiovisual-c++cmakec++17visual-studio-2019

Detect build type (debug/release) in visual studio when using CMake


I have a little game engine in which I need to define some custom macros when it is building in Debug or Release mode.

Here are a few lines of my CMake script which is supposed to do that:

if (CMAKE_BUILD_TYPE STREQUAL "Debug")
    set(OE_BUILD_TYPE_DEFINE "OE_DEBUG")
endif()
    
if (CMAKE_BUILD_TYPE STREQUAL "Release")
    set(OE_BUILD_TYPE_DEFINE "OE_RELEASE")
endif()

if (CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo")
    set(OE_BUILD_TYPE_DEFINE "OE_DEBUG")
endif()

if (CMAKE_BUILD_TYPE STREQUAL "MinSizeRel")
    set(OE_BUILD_TYPE_DEFINE "OE_RELEASE")
endif()

target_compile_definitions(OverEngine PRIVATE
    "_CRT_SECURE_NO_WARNINGS"
    "GLFW_INCLUDE_NONE"

    PUBLIC
    OE_BUILD_TYPE_DEFINE
)

It works great using make or ninja in Linux however on Windows using VisualStudio, the CMAKE_BUILD_TYPE variable is always empty. I know the reason. It is because VS can switch build type without re-running CMake unlike make or ninja generators.

Premake has something called filter which works just fine but for some other reason, I am not using it right now.

How do I set this up?

I am using VisualStudio 2019 16.7.2 and CMake 3.18.2 if it is needed.

EDIT: fixed by replacing those lines with these lines:

target_compile_definitions(OverEngine PRIVATE
    "_CRT_SECURE_NO_WARNINGS"
    "GLFW_INCLUDE_NONE"

    PUBLIC
    $<$<CONFIG:Debug>:OE_DEBUG>
    $<$<CONFIG:Release>:OE_RELEASE>

    $<$<CONFIG:RelWithDebInfo>:OE_DEBUG>
    $<$<CONFIG:MinSizeRel>:OE_RELEASE>
)

Solution

  • You may want to use generator expressions here. They are evaluated at build time and therefore the build type is set even for multi-configuration generators as Visual Studio or Xcode.

    target_compile_definitions(OverEngine
        PRIVATE
          _CRT_SECURE_NO_WARNINGS
          GLFW_INCLUDE_NONE
        PUBLIC
          $<$<CONFIG:Debug>:OE_DEBUG>
          $<$<CONFIG:RelWithDebInfo>:OE_DEBUG>
          $<$<CONFIG:Release>:OE_RELEASE>
          $<$<CONFIG:MinSizeRel>:OE_RELEASE>
    )