如何仅在调试模式下向 cmake 添加符号?

How to add a symbol to cmake, in debug mode only?

我希望下面的代码只在调试模式下编译

main.cpp

    #ifdef __DEBUG__
        int a=1;
        std::cout<<a;
    #endif

将以下内容添加到 cmake

add_compile_options(
  "-D__DEBUG__"
)

add_compile_options(
  "$<$<CONFIG:DEBUG>:-D__DEBUG__>"
)

似乎什么都没做。

我怎样才能达到预期的行为?

尝试设置CMAKE_CXX_FLAGS

set(CMAKE_CXX_FLAGS "-D__DEBUG__")

在源代码中

#if defined(__DEBUG__)
 int a=1;
 std::cout<<a;
#endif

选项 1:NDEBUG

CMake 已经 在发布构建期间定义了 NDEBUG,只需使用:

    #ifndef NDEBUG
        int a=1;
        std::cout<<a;
    #endif

选项 2:target_compile_definitions

配置拼写为Debug,而不是DEBUG。因为你应该 never,ever 使用目录级命令(比如 add_compile_options),我会告诉你如何使用目标-级命令改为:

target_compile_definitions(
  myTarget PRIVATE "$<$<CONFIG:Debug>:__DEBUG__>"
)

也没有必要使用过于通用的 compile options 命令。 CMake 已经提供了一个抽象来确保预处理器 definitions 可用。