Christian Schmitt
Christian Schmitt

Reputation: 892

CMake C++ Set Header DEBUG Variable on Compilation?

is there a way to set a DEBUG variable on compilation?

Based on a Environment Variable or something like a target=release?

Upvotes: 2

Views: 3189

Answers (2)

coincoin
coincoin

Reputation: 4685

You can set CMAKE_BUILD_TYPE to Debug

e.g. cmake -DCMAKE_BUILD_TYPE=Debug [...] which will enable CMAKE_C_FLAGS_DEBUG or CMAKE_CXX_FLAGS_DEBUG.

And append custom flags like this such as enabling a debug macro only at debug build type : set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DENABLE_DEBUG_MACRO")

So this macro will be only enabled whenCMAKE_BUILD_TYPE=Debug.

Or as mentionned in the comment you could also just directly put add_definitions(-DENABLE_DEBUG_MACRO) if you do not care about the build type.

Edit to answer comment

Currently I want to print something to the console in my program (not cmake) if -DCMAKE_BUILD_TYPE=Debug is enabled

For that you can define in your C++ code a macro DEBUG_PRINT which will work only when ENABLE_DEBUG_MACRO is defined.

#ifdef ENABLE_DEBUG_MACRO
#  define DEBUG_PRINT(msg, ...) fprintf(stdout, "[debug] " msg "\n", ##__VA_ARGS__);
#else
#  define DEBUG_PRINT(msg, ...) 
#endif

Live with debug mode

Live without debug mode (no debug message)

Upvotes: 8

Rolf Lussi
Rolf Lussi

Reputation: 615

As @coincoin said, you can set the CMAKE_BUILD_TYPE to debug. If you want to set it as default to debug you can set the variable in the cmake file directly. But don't overwrite it when its already set, like this everyone else can use your cmake file like they are used to.

if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Debug)
endif() 

Upvotes: 0

Related Questions