是否有可能一个字符串化的宏观可变参数? [英] Is it possible to stringify a variadic macro?

查看:130
本文介绍了是否有可能一个字符串化的宏观可变参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gcc (GCC) 4.7.2
c89

是否有可能一个字符串化的宏观可变参数?

Is it possible to stringify a variadic macro?

我有以下的宏观和我要输出从 FMT 和参数。

I have the following macro and I want to output the resulting string from the fmt and arguments.

#define ERROR_MESSAGE(priority, fmt, ...)        \
    do {                                         \
        MODULE_LOG(priority, fmt, ##__VA_ARGS__);\
} while(0)

所以,我只是想获得的 FMT ## __ VA_ARGS __ 这样我就可以完整的字符串它分配给的char * 来对它进行一些额外的操作。

So, I just want to get the complete string of the fmt and the ##__VA_ARGS__ so I can assign it to a char * to perform some additional operations on it.

推荐答案

嗯,没有。 preprocessing发生之前的code甚至编译。它存在于从正在执行的程序完全不同的世界。有一件事你可以做的,是只运行pre-处理步骤和检查输出(使用GCC开关 -E 打印preprocessor输出) 。

Um, no. Preprocessing happens before the code is even compiled. It exists in a completely different universe from the executing program. One thing you can do, is run just the pre-processing step and examine the output (use the gcc switch -E to print the preprocessor output).

关于你能做的最重要的是这个重定向到一个文件,然后读取程序的文件。

About the most you can do is to redirect this to a file, and then read the file in the program.

在进一步的思考,让我从无回退,并更改为可能。看看<一个href=\"http://stackoverflow.com/questions/6707148/foreach-macro-on-macros-arguments/6722112#6722112\">this矿山其他的答案,实现可变参数宏的foreach宏。

On further thought, let me back-off from "no", and change it to "maybe". Take a look at this other answer of mine, that implements a "foreach" macro for variadic macros.

因此​​,使用 APPLYXn (并明确, PPNARG ),你可以申请一个 STR(x)的#X 宏这样的args(NB书面, APPLYXn 可处理多达15个参数):

So, using APPLYXn (and, implicitly, PPNARG), you could apply a STR(x) #x macro to the args like this (n.b. as written, APPLYXn can handle up to 15 arguments):

#define X(x) #x
#define ERROR_MESSAGE(priority, fmt, ...)        \
    "do {MODULE_LOG(" X(priority) X(fmt) APPLYXn(__VA_ARGS__) ");} while(0)"

int main() {
    printf("%s\n", ERROR_MESSAGE(3, "%d", 5) );
    return 0;
}

的gcc -E 产生

# 1 "strvar.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "strvar.c"
# 71 "strvar.c"

int main() {
    printf("%s\n", "do {MODULE_LOG(" "3" "\"%d\"" "5" ");} while(0)" );
    return 0;
}

和编译器将所有这些字符串拼接成一个字符串。

And the compiler will concatenate all these string literals into one string.

这篇关于是否有可能一个字符串化的宏观可变参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆