__attribute__((format(printf, 1, 2))) 用于 MSVC?

2021-12-22 00:00:00 c visual-c++ c++

使用 GCC,我可以指定 __attribute__((format(printf, 1, 2))) ,告诉编译器这个函数采用 vararg 参数,这些参数是 printf 格式说明符.

With GCC, I can specify __attribute__((format(printf, 1, 2))) , telling the compiler that this function takes vararg parameters that are printf format specifiers.

这在我包装的情况下非常有用,例如vsprintf 函数族.我可以有extern void log_error(const char *format, ...) __attribute__((format(printf, 1, 2)));

This is very helpful in the cases where I wrap e.g. the vsprintf function family. I can have extern void log_error(const char *format, ...) __attribute__((format(printf, 1, 2)));

每当我调用这个函数时,gcc 都会检查参数的类型和数量是否符合给定的格式说明符,就像 printf 一样,如果不是,则发出警告.

And whenever I call this function, gcc will check that the types and number of arguments conform to the given format specifiers as it would for printf, and issue a warning if not.

微软的 C/C++ 编译器有没有类似的东西?

Does the Microsoft C/C++ compiler have anything similar ?

推荐答案

虽然 GCC 在启用 -Wformat 时检查格式说明符,但 VC++ 没有这种检查,即使对于标准函数也是如此,因此没有与此等效的 __attribute__ 因为没有等效于 -Wformat.

While GCC checks format specifiers when -Wformat is enabled, VC++ has no such checking, even for standard functions so there is no equivalent to this __attribute__ because there is no equivalent to -Wformat.

我认为微软对 C++ 的重视(通过保持 C++ 的 ISO 合规性来证明,同时只支持 C89)可能是 VC++ 没有格式说明符检查的部分原因;在 C++ 中使用 格式说明符是不必要的.

I think Microsoft's emphasis on C++ (evidenced by maintaining ISO compliance for C++ while only supporting C89) may be in part the reason why VC++ does not have format specifier checking; in C++ using <iostream> format specifiers are unnecessary.

相关文章