C preprocessor tokenization does not expand macro?

对着背影说爱祢 提交于 2020-07-02 18:05:26

问题


1) Why is the macro MSG not expanded in the following expression?

#define MSG Hello
#define HELLO(name)  MSG ## name

void HELLO(Dave) () {}

Using

gcc -E -P test.cpp 

Output:

void MSGDave () {}

MSG name expands to Hello Dave. And MSG # name expands to Hello "Dave". So what causes gcc not to expand MSG ## name?

2) Is there a workaround?

Is there a preprocessor directive like defined(x), such as expand(x)?


回答1:


#define MSG Hello
#define cat(x, y) x ## y
#define cat2(x, y) cat(x, y)
#define HELLO(name) cat2(MSG,name)

Live demo @ ideone.




回答2:


Because macro arguments are not substituted when preceded or followed by a ## operator.

C11 §6.10.3.1 Argument substitution

After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.



来源:https://stackoverflow.com/questions/22369420/c-preprocessor-tokenization-does-not-expand-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!