13

为了调试方便,我编写了以下宏,

1 #ifndef DEF_H
2 #define DEF_H
3 #define DEBUG_MODE
4 #define DEBUG_INFO(message)     \
5         #ifdef DEBUG_MODE       \
6                 cout << message << endl; \
7         #endif                          \
8 #endif

但 gcc 抱怨如下

def.h:4: error: '#' is not followed by a macro parameter
def.h:1: error: unterminated #ifndef

这段代码有什么问题?我在这里错过了一些重要的点吗?

4

3 回答 3

23

#ifdef宏定义中不能有s。你需要把它翻过来:

#ifdef DEBUG_MODE
#define DEBUG_INFO(message) cout << (message) << endl
#else
#define DEBUG_INFO(message)
#endif
于 2012-04-09T14:16:10.797 回答
3

您不能将预处理器指令嵌入另一个预处理器指令(#ifdef DEBUG_MODE在 的定义中DEBUG_INFO)。相反,做类似的事情

#ifdef DEBUG_MODE
# define DEBUG_INFO(message) cout << message << endl
#else
# define DEBUG_INFO(message) 0
#endif

(这仍然不理想;防御性宏编码建议类似

#ifdef DEBUG_MODE
# define DEBUG_INFO(message) do {cout << message << endl;} while (0)
#else
# define DEBUG_INFO(message) 0
#endif

也许一个inline函数会更好。)

于 2012-04-09T14:20:14.180 回答
0

我猜如果你在第 7 行吃了 '\',那么这段代码就可以工作了。

于 2012-04-09T15:53:52.093 回答