Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

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>
)
question from:https://stackoverflow.com/questions/65599308/detect-build-type-debug-release-in-visual-studio-when-using-cmake

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...