DEBUG macros in C++

后端 未结 9 1941
谎友^
谎友^ 2020-12-07 07:54

I just encountered a DEBUG macro in C that I really like

#ifdef DEBUG_BUILD
#  define DEBUG(x) fprintf(stderr, x)
#else
#  define DEBUG(x) do {} while (0)
#e         


        
9条回答
  •  忘掉有多难
    2020-12-07 08:29

    Is the second code snippet analogous to the one in C?

    More or less. It's is more powerful, as you can include <<-separated values in the argument, so with a single argument you get something that would require a variable number of macro arguments in C. On the other hand, there is a slim chance that people will abuse it by including a semicolon in the argument. Or even encounter mistakes due to a forgotten semicolon after the call. So I'd include this in a do block:

    #define DEBUG(x) do { std::cerr << x; } while (0)
    

    Do you have any favourite C++ debug macros?

    I like the one above and use it quite often. My no-op usually just reads

    #define DEBUG(x)
    

    which has the same effect for optimizing compilers. Although the comment by @Tony D below is correct: this can leave some syntax errors undetected.

    I sometimes include a run-time check as well, thus providing some form of a debug flag. As @Tony D reminded me, having an endl in there is often useful as well.

    #define DEBUG(x) do { \
      if (debugging_enabled) { std::cerr << x << std::endl; } \
    } while (0)
    

    Sometimes I also want to print the expression:

    #define DEBUG2(x) do { std::cerr << #x << ": " << x << std::endl; } while (0)
    

    In some macros, I like to include __FILE__, __LINE__ or __func__, but these are more often assertions and not simple debug macros.

提交回复
热议问题