Home > Software engineering >  How to add a symbol to cmake, in debug mode only?
How to add a symbol to cmake, in debug mode only?

Time:12-15

I want the following code to only be compiled in debug mode

main.cpp

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

adding the following to cmake

add_compile_options(
  "-D__DEBUG__"
)

or

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

just doesn't seem to do anything.

How can I achieve desired behavior?

CodePudding user response:

Try setting CMAKE_CXX_FLAGS

set(CMAKE_CXX_FLAGS "-D__DEBUG__")

In source code

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

CodePudding user response:

Option 1: NDEBUG

CMake already defines NDEBUG during release builds, just use that:

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

Option 2: target_compile_definitions

The configuration is spelled Debug, not DEBUG. Since you should never, ever use directory-level commands (like add_compile_options), I'll show you how to use the target-level command instead:

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

There's no need to use the overly generic compile options commands, either. CMake already provides an abstraction for making sure that preprocessor definitions are available.

  • Related