用宏形成变量名

时间:2014-09-04 12:28:25

标签: c++ variables macros

我可以这样做:

#define VERSION 4_1

int32_t myVersion??VERSION;

// What I expect here is that the variable should be generated with name myVersion4_1.
// If possible what should be placed instead of ?? above?

是否可以在C ++中使用上面的宏形成变量名?

2 个答案:

答案 0 :(得分:3)

不完全是您尝试的方式,但您可以执行以下操作:

#define VAR_VERSIONED_NAME(name) name##4_1

int32_t VAR_VERSIONED_NAME(myVersion) = 1;
myVersion4_1 = 2;

VERSION必须是单独的define

#define VERSION 4_1

#define CAT_I(a, b) a ## b
#define CAT(a, b) CAT_I(a, b)
#define VAR_VERSIONED_NAME(name) CAT(name, VERSION)

int VAR_VERSIONED_NAME(myVersion) = 1;
myVersion4_1 = 2;

答案 1 :(得分:1)

您需要等级indirection才能展开VERSION,然后才能粘贴它。

#define VERSION 4_1

#define expand(v) paste(v)
#define paste(v) myVersion ## v

int main()
{
    int expand(VERSION);
    myVersion4_1 = 42;
}