Issue
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?
Solution
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.
Answered By - Alex Reinking