Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#ifdef DEBUG with CMake independent from platform

Tags:

c++

c

cmake

I am using CMake for building my projects on Windows (Visual Studio) as well as on Linux machines(gcc). I'd like to mark some code as "debugging only", like with

#ifdef DEBUG
//some logging here
#endif

The question is: what compiler definition is available on all platforms in the CMake "Debug" build type? DEBUG seems not to exist. (I want to have the logging or whatever only when the build type is Debug.)

like image 863
Philipp Avatar asked Dec 21 '11 14:12

Philipp


3 Answers

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

like image 81
arrowd Avatar answered Nov 12 '22 20:11

arrowd


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.)

like image 34
Lindydancer Avatar answered Nov 12 '22 21:11

Lindydancer


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.

like image 28
jtbr Avatar answered Nov 12 '22 21:11

jtbr