问题
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