C++ Compile Error: gnu_printf is an unrecognized format function type

C++ Compile Error: gnu_printf is an unrecognized format function type

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

warning gnu_printf is an unrecognized format function type

我的旗帜是这样的:

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() 的许多其他用途没有产生任何错误。我对格式错误有点困惑。

显然失败的代码是:

#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