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.)
CMake adds -DNDEBUG
to the CMAKE_C_FLAGS_{RELEASE, MINSIZEREL} by default. So, you can use #ifndef NDEBUG
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With