Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake C++ Set Header DEBUG Variable on Compilation?

Tags:

c++

cmake

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

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

like image 227
Christian Schmitt Avatar asked May 12 '26 17:05

Christian Schmitt


1 Answers

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)

like image 61
coincoin Avatar answered May 14 '26 07:05

coincoin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!