在带引号的字符串中展开宏 [英] Expand macros inside quoted string
问题描述
可能重复:
C 宏创建字符串
我有一个函数,它接受一个 char*
类型的参数,例如 f("string");
如果字符串参数是在函数调用中动态定义的,如何在字符串体中展开宏?
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?
例如:
#define COLOR #00ff00
f("abc COLOR");
相当于
f("abc #00ff00");
但是不执行扩展,函数接收字面意思是abc COLOR
.
but instead the expansion is not performed, and the function receives literally abc COLOR
.
特别是,我需要将宏完全扩展为 "#00ff00"
,以便将这个带引号的标记与传递给 f() 的字符串参数的其余部分连接起来
,包括引号;也就是说,预处理器必须完成他的工作,并欢迎编译器将代码从 f("abc COLOR");
转换为 f("abc "#00ff00"");
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"");
推荐答案
不能在字符串中展开宏,但是可以写
You can't expand macros in strings, but you can write
#define COLOR "#00ff00"
f("abc "COLOR);
请记住,这种连接是由 C 预处理器完成的,它只是连接纯字符串的功能,而不是变量等.
Remember that this concatenation is done by the C preprocessor, and is only a feature to concatenate plain strings, not variables or so.
这篇关于在带引号的字符串中展开宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!