Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug Macro for code block

Tags:

c++

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;


}
like image 817
r m Avatar asked Dec 27 '22 12:12

r m


1 Answers

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 
like image 93
perreal Avatar answered Jan 10 '23 06:01

perreal