1

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)

Onkar N Mahajan
  • 410
  • 3
  • 13
  • You say that suggestions for the question https://stackoverflow.com/questions/8591762/ifdef-debug-with-cmake-independent-from-platform don't work for you, but your answer repeats the approach from [that answer](https://stackoverflow.com/a/8592026/3440745). – Tsyvarev Apr 16 '21 at 11:27
  • Can you specify which version of CMake you are using? As the affects the options available for use. – Antony Peacock Apr 16 '21 at 18:36

3 Answers3

5

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>
)
Antony Peacock
  • 449
  • 4
  • 8
1
  1. Added set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG") to CMakeLists.txt
  2. Created Debug/ directory & cd Debug
  3. cmake -DCMAKE_BUILD_TYPE="Debug" ../

Worked !

Onkar N Mahajan
  • 410
  • 3
  • 13
  • That works, another way, more general (for example to add more sources too) could be: ```if(CMAKE_BUILD_TYPE STREQUAL "Debug") add_definitions(-DDEBUG) endif()``` – Octo Poulos Feb 16 '23 at 10:20
0

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)

viraltaco_
  • 814
  • 5
  • 14