Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DEBUG macro with cmake?

Tags:

c++

c

cmake

I'm new to cmake, so up front, my apologies this question is too basic ..

Question is,

I have logs under #ifdef DEBUG which I want to print only for debug build.

Something like this ..

void func () {

// some code here 

#ifdef DEBUG
    print_log(...) // this portion should execute only for debug builds
#endif 

// some code here

}

How can I achieve this with cmake ?

I have already looked at #ifdef DEBUG with CMake independent from platform and cmakelists debug flag not executing code within "ifdef DEBUG", suggestions here don't seem to work for me.

(project is on Linux platform)

like image 338
Onkar N Mahajan Avatar asked May 10 '26 07:05

Onkar N Mahajan


2 Answers

Modern CMake uses a target-based approach which allows you to specify settings that are restricted to a target as opposed to being global (and affecting all targets). This then gives you the control to specify how the state from targets propagates transitively to dependent targets so as to reduce the visible scope of the state (include paths, library dependencies, compiler defines, compiler flags, etc) to dependent targets. The approach you decide to go with will depend largely on how complex your application is, for instance, how many targets (executable & libraries) exist in the system. The more complex the system the more benefits you in terms of reduced complexity and compile time that you will get from using the target-based approach. In the simplest case to set this up with the modern target based CMake approach you could use the following (where exe is the name of your executable:

add_executable(exe "")
target_sources(exe
    PRIVATE
        main.cpp
)
target_compile_definitions(exe
    PRIVATE
        # If the debug configuration pass the DEBUG define to the compiler 
        $<$<CONFIG:Debug>:DEBUG>
)
like image 163
Antony Peacock Avatar answered May 11 '26 20:05

Antony Peacock


Why do you use

#ifdef DEBUG

instead of the idiomatic (and standardized for <assert.h>)

#ifndef NDEBUG

In my experience CMake will define NDEBUG for release builds by default (at least when using CLion and Xcode). (I double checked. Here's Carlo Wood's answer on a related thread)

like image 31
viraltaco_ Avatar answered May 11 '26 20:05

viraltaco_