Concatenate int to string using C Preprocessor

廉价感情. 提交于 2019-11-27 00:11:50

Classical C preprocessor question....

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#define MAJOR_VER 2
#define MINOR_VER 6
#define MY_FILE "/home/user/.myapp" STR(MAJOR_VER) STR(MINOR_VER)

The extra level of indirection will allow the preprocessor to expand the macros before they are converted to strings.

A working way is to write MY_FILE as a parametric macro:

#define MY_FILE(x,y) "/home..." #x #y

EDIT: As noted by "Lindydancer", this solution doesn't expand macros in arguments. A more general solution is:

#define MY_FILE_(x,y) "/home..." #x #y
#define MY_FILE(x,y) MY_FILE_(x,y)

You can do that with BOOST_PP_STRINGIZE:

#define MAJOR_VER 2
#define MINOR_VER 6
#define MY_FILE "/home/user/.myapp" BOOST_PP_STRINGIZE(MAJOR_VER) BOOST_PP_STRINGIZE(MINOR_VER)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!