使用没有字符串化的#define 参数名称

Use name of #define parameter without stringification

有没有办法在不进行字符串化的情况下将准确的单词传递给 #define?示例用例:

#define NUM 1

#define CREATE_FUN(X) \
void prefix_X() { \ // used exact words passed in
    int x = X; \ // use value later on
}

CREATE_FUN(NUM)

输出如下:

void prefix_NUM() {
    int x = 1;
}

使用令牌连接(##):

#define NUM 1

#define CREATE_FUN(X) \
void prefix_##X() { \
    int x = X; \
}

CREATE_FUN(NUM)
#define CREATE_FUN(X) \
int prefix_##X() { \
    int x = X; \
    return x; \
}

CREATE_FUN(NUM)

您可以使用标记粘贴(##) 运算符:

#define CREATE_FUN(X) int prefix_##X() { int x=X; return x;}

示例用例:

Some compilers provide an extension that allows ## to appear after a comma and before __VA_ARGS__, in which case

  1. the ## does nothing when VA_ARGS is non-empty

  2. removes the comma when VA_ARGS is empty.

这使得定义参数数量可变的宏成为可能,例如 fprintf (stderr, format, ##__VA_ARGS__)