为什么编译器抱怨这个宏声明
为了调试方便,我编写了下面的宏,
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
这段代码出了什么问题? 我在这里错过了一些重点吗?
你不能在宏定义中包含#ifdef
。 你需要把它翻出来:
#ifdef DEBUG_MODE #define DEBUG_INFO(message) cout << (message) << endl #else #define DEBUG_INFO(message) #endif
您不能在另一个预处理程序指令( #ifdef DEBUG_MODE
定义中的#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
函数会更好。)
我想如果你在第7行吃’\’,那么这段代码就可以了。