AKS
AKS

Reputation: 11

Substituting macros within macros in C

I'm trying to make a code-section reusable. My comment snippet below isn't doing what I want it to:

#define NAME ABC 
#define LOG_SIZE NAME##_LEN 

I would like LOG_SIZE to resolve to ABC_LEN. I've tried playing around with the #'s, but haven't been able to get this to work. LOG_SIZE is used all over the code, so I don't want to change the macro to:

#define LOG_SIZE(name) name##_LEN

Is there a way to do this?

Upvotes: 0

Views: 274

Answers (1)

Ray
Ray

Reputation: 2003

The problem is that macro arguments aren't automatically expanded if they would be stringified or concatenated to another token.

C99 6.10.3.1/1:

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.

You can get around this by adding another macro in between the one that passes NAME and the one that concatenates it with _LEN.

#define NAME ABC
#define AFTERX(x) x##_LEN
#define XAFTERX(x) AFTERX(x)
#define LOG_SIZE XAFTERX(NAME)

LOG_SIZE
//evaluates to ABC_LEN

The gcc manual goes into further detail if you're curious, in Section 3.10.6: Argument Prescan

Upvotes: 3

Related Questions