How to use # inside a macro definition - 宏定义嵌套问题

来源:互联网 发布:传奇霸业宝石升级数据 编辑:程序博客网 时间:2024/06/06 03:49

昨天下午写一个宏定义带嵌套的一直报语法错误;

类似这样的一个宏定义

 

#define exmp(par1,par2) {/#ifdef EVAL   /par1 = par2; /#endif  /} 

从网上查了查,具体这里有没有优先级问题还不是很确定
---http://bytes.com/topic/c/answers/472611-possible-write-such-macro
The workaround already has been stated; back to the issue:
- Preprocessing directives can only span one line (the / may hide
that but the above is only one source line) and
there may be only
one preprocessing directive per line.[一行只能有一个预处理指令]
-
Preprocessing directives start the respective line (but for
whitespace)[预处理指令开始在各自的行]
- Thus, you cannot generate preprocessing directives using
preprocessing directives; the language does not allow it.

The reason for the error message is another one:
The preprocessor assumes that the # is the "stringize" preprocessor
operator; this operator surrounds the passed argument by double
quotes ("), i.e. makes them into string literals.【这里的意思应该是说# 有特殊的意义,字符串】

---网页2
http://gcc.gnu.org/ml/gcc-help/2003-11/msg00127.html
#define exmp(par1,par2) { #ifdef EVAL par1 = par2; #endif}

so "#ifdef" and "#endif" are not in the beginning of the lines (where they have to be).
--网页3
http://www.lslnet.com/linux/f/docs1/i43/big5305081.htm
問一個關於宏的問題。
我想在一個帶參的宏中使用條件宏。但是這樣寫編譯不能通過。
[code]
#define DEBUG (1)
#define HANDLE_ERROR(ret,errorNum,msg) /
        if(0 != (ret) ) /
        {/
#ifdef (DEBUG)/
        cout<<(msg)<<endl;/
#endif/
        cout<<"ret = "<<(ret)<<endl;/
        return ret;/
        }
[/code]
g++ -g testMaco.cpp -o testMaco.bin
testMaco.cpp:8:2: '#' is not followed by a macro parameter
testMaco.cpp: In function `int main()':
testMaco.cpp:24: error: `REC_HANDLE_ERROR_RET' was not declared in this scope
帶參的宏中能不能使用條件宏呢?如果能使用的話,該怎麼寫?

我試了半天都不行啊,好像識別條件宏高於宏替換,還是改成這樣吧
#define DEBUG (1)
#ifdef DEBUG
#define HANDLE_ERROR(ret,errorNum,msg) /
        if(0 != (ret) ) /
        {/
        cout<<(msg)<<endl;/
        cout<<"ret = "<<(ret)<<endl;/
        return ret;/
        }
#else
#define HANDLE_ERROR(ret,errorNum,msg) /
        if(0 != (ret) ) /
        {/
        cout<<"ret = "<<(ret)<<endl;/
        return ret;/
        }
#endif

--网页4
http://gcc.gnu.org/ml/gcc-help/2003-11/msg00124.html
You cannot embed preprocessor directives in a macro expansion.  They neither get evaluated at the time of macro definition, nor at the time of instantiation.Perhaps that's unfortunate.  But that's the way it is.
这里说的是不能再宏定义中嵌套预处理指令,这里应该牵扯到一定的优先级问题吧,希望知道的可以 说说。。。

参考网页:
http://bytes.com/topic/c/answers/472611-possible-write-such-macro
http://gcc.gnu.org/ml/gcc-help/2003-11/msg00127.html
http://www.lslnet.com/linux/f/docs1/i43/big5305081.htm
http://gcc.gnu.org/ml/gcc-help/2003-11/msg00124.html

 

原创粉丝点击