Combining two #defined symbols in C++ preprocessor

2019-06-16 06:54发布

I want to do:

#define VERSION XY123
#define PRODUCT MyApplication_VERSION

so that PRODUCT is actually MyApplication_XY123. I have tried playing with the merge operator ## but with limited success...

#define VERSION XY123
#define PRODUCT MyApplication_##VERSION

=> MyApplication_VERSION

#define VERSION XY123
#define PRODUCT MyApplication_##(VERSION)

=> MyApplication_(XY123) - close but not quite

Is what I want possible?

3条回答
疯言疯语
2楼-- · 2019-06-16 07:26

The ## operator acts before argument substitution has taken place. The classical solution is to use a helper:

#define CONCAT2(a, b) a ## b
#define CONCAT(a, b) CONCAT2(a, b)

CONCAT(MyApplication_, VERSION)
查看更多
Anthone
3楼-- · 2019-06-16 07:32

Token pasting works with arguments to macros. So try this

#define VERSION XY123
#define PASTE(x) MyApplication_ ## x
#define PRODUCT PASTE(VERSION)
查看更多
相关推荐>>
4楼-- · 2019-06-16 07:48

All problems in computer science can be solved by an extra level of indirection:

#define JOIN_(X,Y) X##Y
#define JOIN(X,Y) JOIN_(X,Y)
#define VERSION XY123
#define PRODUCT JOIN(MyApplication_,VERSION)
查看更多
登录 后发表回答