用C DEBUG宏++ [英] DEBUG macros in C++

查看:215
本文介绍了用C DEBUG宏++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是用C遇到了一个DEBUG宏,我真的很喜欢

  #IFDEF DEBUG_BUILD
#定义DEBUG(X)fprintf中(标准错误,X)
#其他
#定义DEBUG(X)做{}而(0)
#万一

我猜一个C ++模拟将是: -

  #IFDEF DEBUG_BUILD
#定义DEBUG(x)的CERR<< X
#其他
#定义DEBUG(X)做{}而(0)
#万一


  1. 是第二code段类似于一个是C?

  2. 你有没有最喜欢的C ++调试宏?

编辑:
通过调试宏我的意思是跑在调试模式的程序而可能会派上用场的宏。


解决方案

是第二code段类似于一个是C?

更多或更少。它的功能更强大,因为你可以包括<< 中的参数 - 分隔值,因此用一个参数,你得到的东西,需要一个可变数量的宏参数在C.在另一方面,有一个渺茫的机会,人们会通过在参数分号滥用它。甚至encouter错误是由于调用后一个被遗忘的分号。所以我想这包括在做块:

 将#define DEBUG(X){做的std :: CERR<< X; }而(0)

你有没有最喜欢的C ++调试宏?

我喜欢的人上面,而且经常使用它。我无操作通常只是读

 将#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

  1. Is the second code snippet analogous to the one in C?
  2. Do you have any favorite C++ debug macros?

EDIT : By "Debug Macros" I mean "macros that might come in handy while running a program in debug mode".

解决方案

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 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)

Do you have any favorite 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 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.

这篇关于用C DEBUG宏++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆