【问题标题】:C++ Compile Error: gnu_printf is an unrecognized format function typeC++ 编译错误:gnu_printf 是无法识别的格式函数类型
【发布时间】:2018-08-26 01:43:16
【问题描述】:

编译时,我在 .h 文件中的 3 行不同的代码上收到相同的警告,例如:

警告gnu_printf 是无法识别的格式函数类型

我的标志是这样的:

CFLAGS += -Wall -Wextra -Wformat -Wno-ignored-qualifiers -Wformat-security -Wno-unused-parameter \

下面产生此错误的三行代码示例:

int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...);

std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...);

bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...);

我在这个文件中有许多其他的printf() 用法,它们没有产生任何错误。我对格式错误有点困惑。

【问题讨论】:

  • 什么是ATTR_WARN_PRINTF()
  • @Azeem /* This GNU C extension enables the compiler to check the format string against the parameters provided. * X is the number of the "format string" parameter, and Y is the number of the first variadic parameter. * Parameters count from 1. */ #ifdef __GNUC__ #define ATTR_WARN_PRINTF(X,Y) __attribute__((format(gnu_printf,X,Y))) #else #define ATTR_WARN_PRINTF(X,Y) #endif
  • 对。您能否发布一个导致此警告的最小代码示例?一个可以单独编译的。谢谢。
  • 您可以查看第 172-198 行以查看错误的来源。 link
  • 你用的是什么编译器?铛? MinGW 上的东西?什么版本?

标签: c++ printf compiler-warnings


【解决方案1】:

显然失败的代码是:

#ifdef __GNUC__ 
#define ATTR_WARN_PRINTF(X,Y) __attribute__((format(gnu_printf,X,Y))) 
#else 
#define ATTR_WARN_PRINTF(X,Y)
#endif
int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...);

std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...);

bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...);

这似乎适用于版本 4.4.7 和 gcc trunk (9.0.0) 之间的任何 gcc。 GCC 4.1.2 失败:

<source>:7: warning: 'gnu_printf' is an unrecognized format function type

此外,clang 在这方面总是失败:

<source>:7:5: warning: 'format' attribute argument not supported: gnu_printf [-Wignored-attributes]

但从最初的问题来看,GCC 的问题似乎太旧了。要解决此问题,请检查 GCC 版本号:

#if defined(__GNUC__) && ((__GNUC__ == 4 && __GNUC_MINOR__>= 4) || __GNUC__ > 4)
#  define ATTR_WARN_PRINTF(X,Y) __attribute__((format(gnu_printf,X,Y))) 
#elif defined(__GNUC__)
#  define ATTR_WARN_PRINTF(X,Y) __attribute__((format(printf,X,Y))) 
#else 
#  define ATTR_WARN_PRINTF(X,Y)
#endif

也许将格式限制为printf而不是gnu_printf更好,这样可以简化上述条件。

编辑: 可以在 GCC 历史上找到,gnu_printf 格式是在 gcc-4.4.0 中添加的 commit r133365。据我了解,它只是printf 的别名,并且添加了gnu 前缀以允许区分不同编译器的printf,例如可能是ms_printf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2019-11-24
    • 2023-03-11
    • 2016-05-25
    • 1970-01-01
    相关资源
    最近更新 更多