如何为C宏字符串化char缓冲区

Dan*_*iel 1 c macros stringification c-preprocessor

我有一个LOG(fmt, ...)宏使用char buf[]as 时不起作用fmt.

下面的代码是代码的完整(实际上)工作示例.在some_function(),我试图以LOG()两种不同的方式使用,但只有第一种方法有效.

为了解决这个问题,我尝试过#define LOG_STR(x) #x以下方式:

  1. 为了字符串化是什么在接收#define LOG应用LOG_STR()format像这样:LOG_STR(format); 和

  2. 申请LOG_STR()直接到这种印刷:LOG(LOG_STR(fmt), 6).

这两种方法都不起作用,事实上我从中得到了段错误.

    #include <stdio.h>

    #define LOG(format, ...) do {                             \
                fprintf(stderr, "[LOG] " format " [%s]\n",    \
                        ##__VA_ARGS__, __func__);             \
            } while (0)

    static void some_function()
    {
        // This works
        LOG("This is a number: %d", 5);

        // This does not work
        const char fmt[] = "This is a number: %d";
        LOG(fmt, 6);
    }

    int main(void)
    {
        some_function();
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

当我编译上面的代码时,我收到以下错误:

$ gcc -o log-macro-str log-macro-str.c
log-macro-str.c: In function ‘some_function’:
log-macro-str.c:15:6: error: expected ‘)’ before ‘fmt’
  LOG(fmt, 6);
      ^
log-macro-str.c:4:29: note: in definition of macro ‘LOG’
    fprintf(stderr, "[LOG] " format " [%s]\n",    \
                             ^~~~~~
Run Code Online (Sandbox Code Playgroud)

我想LOG()在两种方式中使用,无论是否使用some_function()修饰符,只打印字符串.我怀疑我可能需要将format部分字符串化,但我似乎无法正确地做到这一点.

我做错了什么,我该如何解决这个问题?

Eri*_*hil 5

stringify运算符#在宏中将预处理程序标记转换为字符串文字中的文本.它不会将char缓冲区的内容更改为编译时字符串文字.

要使宏工作,请使用多个fprintf语句:

#define LOG(format, ...) do {                          \
            fprintf(stderr, "[LOG] ");                 \
            fprintf(stderr, format, __VA_ARGS__);      \
            fprintf(stderr, " [%s]\n", __func__);      \
        } while (0)
Run Code Online (Sandbox Code Playgroud)

  • 重要的一点是stringify运算符和字符串文字串联是编译时操作,而char缓冲区是运行时实体,因此这不可行.您无法在编译时连接尚未知的字符串. (2认同)