有没有办法定义一个宏,将表达式(即int)转换为字符串文字?

时间:2014-06-30 10:02:10

标签: c macros

有没有办法像这样定义:

#define PUTVAL 0x00

#define foo(x) ("x")

int main()
{
    char *szFoo = foo(PUTVAL);

    return 0;
}

并通过宏修改它,szFoo将指向包含“0x00”的stringliteral 不是“x”?

1 个答案:

答案 0 :(得分:5)

是的,你必须使用两个级别的宏,它被称为 stringification

http://gcc.gnu.org/onlinedocs/cpp/Stringification.html

 #define xstr(s) str(s)
 #define str(s) #s
 #define foo 4
 str (foo)
      ==> "foo"
 xstr (foo)
      ==> xstr (4)
      ==> str (4)
      ==> "4"