简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM