Expand macros inside quoted string [duplicate]

房东的猫 提交于 2019-11-30 14:31:07

问题


Possible Duplicate:
C Macros to create strings

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?

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.

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\"");


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/12958925/expand-macros-inside-quoted-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!