I am trying to create a macro that executes blocks of code only if it's a debug build. I've managed to make one that executes one line only if debug is enabled, but i cannot figure out how to do a whole block of code.
the one line macro is 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;
}
Wrap the macro inside a do-while
loop so that you avoid problems when using your macro in conditional statements such as if (cond) DBG_ONLY(i++; j--;)
. It also creates a new scope for debug only 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 statements like int i,j
. For that, we need a variadic macro I guess:
#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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With