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?
Try setting CMAKE_CXX_FLAGS
set(CMAKE_CXX_FLAGS "-D__DEBUG__")
In source code
#if defined(__DEBUG__)
int a=1;
std::cout<<a;
#endif
NDEBUG
CMake already defines NDEBUG
during release builds, just use that:
#ifndef NDEBUG
int a=1;
std::cout<<a;
#endif
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.