Question

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)?

Was it helpful?

Solution 2

#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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top