#ifdef DEBUG with CMake independent from platform

I would suggest that you add your own definition. The CMake symbol CMAKE_C_FLAGS_DEBUG can contain flags only used in debug mode. For example:

C:

set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DMY_DEBUG")

C++:

set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DMY_DEBUG")

In your code you can then write the following:

#ifdef MY_DEBUG
// ...
#endif

(Maybe, you would have to use "/DMY_DEBUG" for visual studio.)


In CMake >= 2.8, use target_compile_definitions:

target_compile_definitions(MyTarget PUBLIC "$<$<CONFIG:DEBUG>:DEBUG>")

When compiling in Debug mode, this will define the DEBUG symbol for use in your code. It will work even in IDEs like Visual Studio and Xcode for which cmake generates a single file for all compilation modes.

You have to do this for each target [1]. Alternatively you can use add_compile_options (Cmake >= 3.0):

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

Note that recent versions of Visual C++ (at least since VS2015) allow either / or - for parameters, so it should work fine across compilers. This command is also useful for other compile options you might like to add ("/O2" in release mode for MSVC or "-O3" for release mode in G++/Clang)

[1] : Note: in CMake >= 3.12 (currently beta) there is also an add_compile_definitions that supports generator expressions, which affects all targets.


CMake adds -DNDEBUG to the CMAKE_C_FLAGS_{RELEASE, MINSIZEREL} by default. So, you can use #ifndef NDEBUG.

Tags:

C++

C

Cmake