调试注释和C/C++宏

4

我是使用g++编译器的,我希望我的c ++代码中的某些行可以根据我的配置进行注释或取消注释。

我意识到我可以这样做:

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

但我更希望所有内容都在同一行上:

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

...使用DEBUG作为//的宏定义。但是编写#define DEBUG //没有任何效果。有人能告诉我该怎么做吗?

5个回答

5
这是一种实现方式:
#ifdef DEBUG
#define DEBUG_LOG(x) std::cout << x << std::endl;
#else
#define DEBUG_LOG(x)
#endif

DEBUG_LOG("foo")

此外,您可以在此方法中编写 DEBUG_LOG( "variable=" << variable );,因此您可以使用cout中的所有内容。 - Galimov Albert

4

但我更希望所有内容都在一行上:
#define DEBUG //

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

您的方法永远不会起作用。它不能工作。之所以不存在定义成为注释序列开始的宏机制,是因为在预处理器符号定义时注释已经被剥离掉了。


3

来自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;

+1。你确实在一行代码中完成了它,并且它可以在g++上运行。(由于缺乏可移植性,我无法在当前的项目中使用它。) - JellicleCat

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

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>使用它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接