C语言 在带引号的字符串中展开宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12958925/
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 04:09:11  来源:igfitidea点击:

Expand macros inside quoted string

cmacrosc-preprocessorc-strings

提问by davide

Possible Duplicate:
C Macros to create strings

可能的重复:
创建字符串的 C 宏

I have a function which accepts one argument of type char*, like f("string");
If the string argument is defined by-the-fly in the function call, how can macros be expanded within the string body?

我有一个函数,它接受一个类型的参数char*,比如f("string");
如果字符串参数是在函数调用中即时定义的,那么宏如何在字符串主体中展开?

For example:

例如:

#define COLOR #00ff00
f("abc COLOR");

would be equivalent to

将相当于

f("abc #00ff00");

but instead the expansion is not performed, and the function receives literally abc COLOR.

而是不执行扩展,并且函数从字面上接收abc COLOR.

In particular, I need to expand the macro to exactly \"#00ff00\", so that this quoted token is concatenated with the rest of the string argument passed to f(), quotes included; that is, the preprocessor has to finish his job and welcome the compiler transforming the code from f("abc COLOR");to f("abc \"#00ff00\"");

特别是,我需要将宏扩展为精确\"#00ff00\",以便这个带引号的标记与传递给的字符串参数的其余部分连接f(),包括引号;也就是说,预处理器必须完成他的工作并欢迎编译器将代码从 转换f("abc COLOR");f("abc \"#00ff00\"");

回答by tomahh

You can't expand macros in strings, but you can write

你不能在字符串中展开宏,但你可以写

#define COLOR "#00ff00"

f("abc "COLOR);

Remember that this concatenation is done by the C preprocessor, and is only a feature to concatenate plain strings, not variables or so.

请记住,这种连接是由 C 预处理器完成的,并且只是连接普通字符串的功能,而不是变量等。

回答by singpolyma

#define COLOR "#00ff00"
f("abc "COLOR);