使用C预处理器将int连接到字符串 [英] Concatenate int to string using C Preprocessor
问题描述
我试图弄清楚如何使用 C 预处理器将#define
'd int连接到#define
'd字符串.我的编译器是CentOS 5上的GCC 4.1.该解决方案也应该适用于MinGW.
I'm trying to figure out how I can concatenate a #define
'd int to a #define
'd string using the C Preprocessor. My compiler is GCC 4.1 on CentOS 5. The solution should also work for MinGW.
我想在字符串上附加一个版本号,但是唯一可以使它起作用的方法是将版本号的副本定义为字符串.
I'd like to append a version number onto a string, but the only way I can get it to work is to make a copy of the version number defines as strings.
我能找到的最接近的东西是引用宏参数的方法,但不适用于#define
s
The closest thing I could find was a method of quoting macro arguments, but it doesn't work for #define
s
这是行不通的.
#define MAJOR_VER 2
#define MINOR_VER 6
#define MY_FILE "/home/user/.myapp" #MAJOR_VER #MINOR_VER
如果没有#
,它也不起作用,因为值是数字,并且会扩展为"/home/user/.myapp" 2 6
,这对 C 无效.
It doesn't work without the #
s either because the values are numbers and it would expand to "/home/user/.myapp" 2 6
, which isn't valid C.
这确实有效,但是我不喜欢定义版本的副本,因为我也确实需要它们作为数字.
This does work, but I don't like having copies of the version defines because I do need them as numbers as well.
#define MAJOR_VER 2
#define MINOR_VER 6
#define MAJOR_VER_STR "2"
#define MINOR_VER_STR "6"
#define MY_FILE "/home/user/.myapp" MAJOR_VER_STRING MINOR_VER_STRING
推荐答案
经典C预处理程序问题....
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.
这篇关于使用C预处理器将int连接到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!