Macro debugging for code block

I am trying to create a macro that executes blocks of code only if it is a debug assembly. I managed to create one that runs a single line only if debug is turned on, but I can't figure out how to make an entire block of code.

single line macro below:

#include <iostream> //error checking #if defined(DEBUG) | defined(_DEBUG) #ifndef DBG_ONLY #define DBG_ONLY(x) (x) #endif #else #ifndef DBG_ONLY #define DBG_ONLY(x) #endif #endif int main () { DBG_ONLY(std::cout << "yar" << std::endl); return 0; } 
+4
source share
2 answers

Wrap the macro inside a do-while to avoid problems when using your macro in conditional statements such as if (cond) DBG_ONLY(i++; j--;) . It also creates a new area for debugging declarations:

 #if defined(DEBUG) | defined(_DEBUG) #ifndef DBG_ONLY #define DBG_ONLY(x) do { x } while (0) #endif #else #ifndef DBG_ONLY #define DBG_ONLY(x) #endif #endif int main () { DBG_ONLY( std::cout << "yar" << std::endl; std::cout << "yar" << std::endl; std::cout << "yar" << std::endl; std::cout << "yar" << std::endl; ); return 0; } 

This will fail if you have expressions such as int i,j . To do this, we need a variable macro, which I assume:

 #if defined(DEBUG) | defined(_DEBUG) #ifndef DBG_ONLY #define DBG_ONLY(...) do { __VA_ARGS__; } while (0) #endif #else #ifndef DBG_ONLY #define DBG_ONLY(...) #endif #endif 
+6
source

If this is for β€œarbitrary” debugging code (as opposed to strict logging), then one rough option is simple #if / #endif .

 #if defined(DEBUG) | defined(_DEBUG) #define DBG_ONLY #endif ... #ifdef DBG_ONLY // Blah blah blah #endif 

This is definitely uglier than @perreal's solution, but it avoids any problems associated with defining the scope, and works in all variants of the language (and any other problems that we have not thought about!).

It is also true that this is conditional code, and therefore has the ability to get bad due to synchronization (because it is not always checked by the compiler). But this also applies to the macro solution.

There is another advantage; in a decent IDE (like Eclipse CDT), your debugging code will be highlighted differently.

+4
source

All Articles