【问题标题】:How can I stringify a macro using a macro?如何使用宏对宏进行字符串化?
【发布时间】:2018-02-23 07:11:52
【问题描述】:
#define A_1 {2,1124,124110,2,0,20,5121,0,21241,10}
#define SFY(macro) #macro

void func(char* s, int i) {
    printf("%d %s", i, s);
}

int main (void) {
    int a[10] = A_1;
    func(SFY(A_1), 2);
}

我想要的输出是:

2 {2,1124,124110,2,0,20,5121,0,21241,10}

如何将这样的宏字符串化?

【问题讨论】:

  • 每当你发现自己需要这样奇怪的东西时,这通常意味着你的程序设计已经脱轨,你应该退后一步解决这个潜在的问题。例如,您不能使用const struct 的表实际上是否有原因。

标签: c c-preprocessor stringification


【解决方案1】:

你需要再增加一层间接来扩展宏(因为它包含逗号,你必须去可变参数):

#define A_1 {2,1124,124110,2,0,20,5121,0,21241,10}
#define SFY_2(...) #__VA_ARGS__
#define SFY(macro) SFY_2(macro)

void func(char* s, int i) {
    printf("%d %s", i, s);
}

int main (void) {
    int a[10] = A_1;
    func(SFY(A_1), 2);
}

[Live example]

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多