3

我正在使用 g++ 编译器,我希望我的 c++ 代码的某些行被注释掉或不被注释,这取决于我的配置。

我意识到我可以这样做:

#ifdef DEBUG
cout << "foo" << endl;
#endif

但我宁愿这一切都在一条线上:

#define DEBUG //
DEBUG cout << "foo" << endl;

...DEBUG作为//. 但是写作#define DEBUG //一无所获。谁能告诉我该怎么做?

4

5 回答 5

4

这是一种方法:

#ifdef DEBUG
#define DEBUG_LOG(x) std::cout << x << std::endl;
#else
#define DEBUG_LOG(x)
#endif

DEBUG_LOG("foo")
于 2012-09-29T19:39:10.960 回答
3

但我宁愿这一切都在一条线上:
#define DEBUG //

人们已经给出了如何实现你想要的很好的例子,但没有人评论你的方法为什么不起作用。

你的方法永远不会奏效。它行不通。没有机制可以定义成为注释序列开始的宏,原因很简单,即在定义预处理器符号时注释不存在。它们已经被剥离了。

于 2012-09-29T20:28:14.840 回答
2

Dobbs 博士文章中的一个技巧:

#if _DEBUG
// dbgInC defined as "printf" or other custom debug function
#define dbgInC printf
// dbgInCpp defined as "cout" or other custom debug class
#define dbgInCpp cout
#else
// dbgInC defined as null [1]
#define dbgInC
// dbgInCpp defined as "if(0) cerr" or "if(1); else cerr"
#define dbgInCpp if(0) cerr
#endif

这具有允许多行语句的优点:

dbgInCpp << "Debug in C++: "
<< a // a is an integer
<< b /* b is char array */
<< c // c is a float
<< endl;
于 2012-09-29T19:39:51.247 回答
0

它在 C 中不是惯用的。更喜欢使用通常的形式,例如

#ifdef DEBUG
    count << "foo" << endl;
#endif

或(如assert):

#ifndef NDEBUG
    count << "foo" << endl;
#endif

为了可读性。您还可以将此代码封装在宏中:

#ifdef DEBUG
#define PRINT_DEBUG(s) cout << s << endl
#else
#define PRINT_DEBUG(s) (void)0
#endif
于 2012-09-29T19:38:58.223 回答
0

你可能有

#ifndef NDEBUG
#define DBGOUT(Out) cout << __FILE__ << ":" << __LINE__ << ":" \
  << Out << endl
#else
#define DBGOUT(Out) do {} while(0)
#endif

并在您的代码中使用,例如

DBGOUT("x is " << x);

我使用 NDEBUG 符号,因为<assert.h><cassert>使用它。

于 2012-09-29T19:40:27.057 回答