避免在printf周围的包装器中发出警告 [英] Avoid warning in wrapper around printf

查看:54
本文介绍了避免在printf周围的包装器中发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写的小C库中有一个错误报告功能。除了普通的 error 函数之外,我还想提供一个 errorf 函数,以便轻松地将信息嵌入错误消息中。 / p>

I have an error reporting functionality in my little C library I'm writing. I want to provide an errorf function in addition to the plain error function to allow embedding information in error messages easily.

/*
 * Prints a formatted error message. Use it as you would use 'printf'. See the
 * 'sio_error' function.
 */
void sio_errorf(const char *format, ...) {
    // Print the error prefix                           
    if (g_input == STDIN) fputs("error: ", stderr);
    else fprintf(stderr, "%s: ", g_progname);

    // Pass on the varargs on to 'vfprintf'. 
    va_list arglist;
    va_start(arglist, format);
    // This may produce the following warning -- ignore it:
    //     warning: format string is not a string literal
    vfprintf(stderr, format, arglist);
    va_end(arglist);
    fputc('\n', stderr);
}

问题是,我得到了这个警告(使用clang 4.0和-万能开关):

The problem is, I get this warning (compiling with clang 4.0 with the -Weverything switch):


警告:格式字符串不是字符串文字

warning: format string is not a string literal

我知道为什么这样做会很糟糕。有什么办法可以消除此警告?我能以某种方式强制将 format 参数 sio_errorf 设为字符串文字,以便编译器知道它将始终是,而我只是将其传递下去?

I understand why doing this would be bad. Is there any way I can get rid of this warning? Can I somehow enforce that the format argument sio_errorf be a string literal, so that the compiler knows that it always will be, and that I'm simply passing it on?

我知道我可以使用 -Wno-format-nonliteral ,但只有其他人也要手动编译时,他们才不会这样做。我希望源代码中的某些内容可以消除警告。

I know I can use -Wno-format-nonliteral, but only if other people are going to manually compile it too, they won't do that. I'd rather something in the source code that silences the warning.

理想情况下,如果传递给 sio_errorf 实际上 不是文字,但是我不确定是否可行。

Ideally I would still get the warning if the string I passed to sio_errorf actually isn't a literal, but I'm not sure if that's possible.

推荐答案

如果您使用的是GCC或其亲戚之一,请在声明中尝试以下属性:

If you're using GCC or one of its relatives, try an attribute on the declaration:

void sio_errorf(const char *format, ...) __attribute__((format(printf, 1, 2)));

要将属性添加到定义中,可以使用以下方法:

To add the attribute to a definition, you can use this:

__attribute__((format(printf, 1, 2)))
    static void sio_errorf(const char *format, ...) {
      ....

这篇关于避免在printf周围的包装器中发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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