C语言 使用 C 预处理器将 int 连接到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5459868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:11:37  来源:igfitidea点击:

Concatenate int to string using C Preprocessor

cc-preprocessorstringification

提问by jonescb

I'm trying to figure out how I can concatenate a #define'd int to a #define'd string using the CPreprocessor. My compiler is GCC 4.1 on CentOS 5. The solution should also work for MinGW.

我试图弄清楚如何使用C预处理器将#define'd int连接到#define'd 字符串。我的编译器是 CentOS 5 上的 GCC 4.1。该解决方案也适用于 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 #defines

我能找到的最接近的是引用宏参数的方法,但它不适用于#defines

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.

没有#s 也不起作用,因为值是数字并且它会扩展为"/home/user/.myapp" 2 6,这不是有效的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

回答by Lindydancer

Classical C preprocessor question....

经典的 C 预处理器问题....

#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.

额外的间接级别将允许预处理器在将宏转换为字符串之前对其进行扩展。

回答by Giuseppe Guerrini

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

一种工作方法是将 MY_FILE 写为参数宏:

#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:

编辑:正如“Lindydancer”所指出的,此解决方案不会在参数中扩展宏。更通用的解决方案是:

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

回答by Maxim Egorushkin

You can do that with BOOST_PP_STRINGIZE:

你可以用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)