使用 C 预处理器将 int 连接到字符串
我试图弄清楚如何使用 C 预处理器将 #define
'd int 连接到 #define
'd 字符串。我的编译器是 CentOS 5 上的 GCC 4.1。该解决方案也适用于 MinGW。
我想将版本号附加到字符串上,但使其工作的唯一方法是将版本号定义为字符串的副本。
我能找到的最接近的方法是引用宏参数的方法,但它不适用于 #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。
这确实有效,但我不喜欢拥有版本定义的副本,因为我也需要它们作为数字。
#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
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.
The closest thing I could find was a method of quoting macro arguments, but it doesn't work for #define
s
This is does not work.
#define MAJOR_VER 2
#define MINOR_VER 6
#define MY_FILE "/home/user/.myapp" #MAJOR_VER #MINOR_VER
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
经典 C 预处理器问题....
额外的间接级别将允许预处理器在将宏转换为字符串之前扩展宏。
Classical C preprocessor question....
The extra level of indirection will allow the preprocessor to expand the macros before they are converted to strings.
一种工作方法是将 MY_FILE 编写为参数宏:
编辑:正如“Lindydancer”所述,此解决方案不会扩展参数中的宏。更通用的解决方案是使用两步宏:
A working way is to write MY_FILE as a parametric macro:
EDIT: As noted by "Lindydancer", this solution doesn't expand macros in arguments. A more general solution is using two-step macros:
您可以使用 BOOST_PP_STRINGIZE 来做到这一点:
You can do that with BOOST_PP_STRINGIZE: