我是使用g++编译器的,我希望我的c ++代码中的某些行可以根据我的配置进行注释或取消注释。
我意识到我可以这样做:
#ifdef DEBUG
cout << "foo" << endl;
#endif
但我更希望所有内容都在同一行上:
#define DEBUG //
DEBUG cout << "foo" << endl;
...使用DEBUG
作为//
的宏定义。但是编写#define DEBUG //
没有任何效果。有人能告诉我该怎么做吗?
我是使用g++编译器的,我希望我的c ++代码中的某些行可以根据我的配置进行注释或取消注释。
我意识到我可以这样做:
#ifdef DEBUG
cout << "foo" << endl;
#endif
但我更希望所有内容都在同一行上:
#define DEBUG //
DEBUG cout << "foo" << endl;
...使用DEBUG
作为//
的宏定义。但是编写#define DEBUG //
没有任何效果。有人能告诉我该怎么做吗?
#ifdef DEBUG
#define DEBUG_LOG(x) std::cout << x << std::endl;
#else
#define DEBUG_LOG(x)
#endif
DEBUG_LOG("foo")
但我更希望所有内容都在一行上:
#define DEBUG //
人们已经给出了如何实现您想要的内容的好例子,但没有人评论为什么您的方法不起作用。
您的方法永远不会起作用。它不能工作。之所以不存在定义成为注释序列开始的宏机制,是因为在预处理器符号定义时注释已经被剥离掉了。
来自Dr. 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;
这在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
你可能有
#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>
使用它。
DEBUG_LOG( "variable=" << variable );
,因此您可以使用cout中的所有内容。 - Galimov Albert