Combining two #defined symbols in C++ preprocessor

谁说胖子不能爱 提交于 2019-12-08 15:58:43

问题


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?


回答1:


Token pasting works with arguments to macros. So try this

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



回答2:


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)



回答3:


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)


来源:https://stackoverflow.com/questions/16591642/combining-two-defined-symbols-in-c-preprocessor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!