更新时间:2023-12-01 08:25:04
更多或更少。它的功能更强大,因为你可以包括<<
中的参数 - 分隔值,因此用一个参数,你得到的东西,需要一个可变数量的宏参数在C.在另一方面,有一个渺茫的机会,人们会通过在参数分号滥用它。甚至encouter错误是由于调用后一个被遗忘的分号。所以我想这包括在做块:
将#define DEBUG(X){做的std :: CERR<< X; }而(0)
我喜欢的人上面,而且经常使用它。我无操作通常只是读
将#define DEBUG(X)
具有用于优化编译器相同的效果。虽然低于@Tony D中的评论是corret:这可以留下一些语法错误未被发现
我有时包括运行时检查为好,从而提供某种形式的调试标志的。由于@TonyÐ提醒我,有一个在ENDL往往存在也是有用的。
将#define DEBUG(X)做{\\
如果(debugging_enabled){性病:: CERR<<点¯x所述&;&下;的std :: ENDL; } \\
}而(0)
有时我也在想打印前pression:
的#define DEBUG2(X){做的std :: CERR<< #X<< :&所述;&下;点¯x所述&;&下;的std :: ENDL; }而(0)
在一些宏,我想包括 __ FILE __
, __ LINE __
或 __ FUNC __
,但这些往往断言,而不是简单的调试宏。
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)
#endif
I'm guessing a C++ analogue would be :-
#ifdef DEBUG_BUILD
# define DEBUG(x) cerr << x
#else
# define DEBUG(x) do {} while (0)
#endif
EDIT : By "Debug Macros" I mean "macros that might come in handy while running a program in debug mode".
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 encouter 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)
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 corret: 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.