如何禁止显示源文件中特定宏定义的零参数的 GCC 可变参数宏参数警告

How to suppress GCC variadic macro argument warning for zero arguments for a particular macro definition within a source file

本文关键字:参数 GCC 变参 警告 宏定义 禁止显示 源文件      更新时间:2023-10-16

我想抑制 GCC 可变参数宏参数警告零参数,例如通过以下方式生成:

// for illustration purposes only:
int foo(int i) { return 0; };
#define FOO(A, ...) foo(A, ##__VA_ARGS__)
FOO(1);
     ^  warning: ISO C++11 requires at least one argument for the "..." in a variadic macro

使用 GCC 5.3.0 时,源文件中的特定宏定义。

在 clang 中,此操作如下:

// ... large file
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#define FOO(A, ...) foo(A, ##__VA_ARGS__)
#pragma clang diagnostic pop
// ... large file
// not necessary on the same file
FOO(1);  // doesnt trigger the warning

在 gcc 中,看起来-pedantic是一种神奇的警告类型,因此以下内容不起作用:

// ... large file
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#define FOO(A, ...) foo(A, ##__VA_ARGS__)
#pragma GCC diagnostic pop
// ... large file

需要明确的是,除了这个特定的代码片段之外,应该在整个程序中启用警告。这是关于细粒度控制。在GCC中禁用整个程序的警告可以通过不将-pedantic传递给编译器来实现。

您应该能够使用

#pragma GCC system_header

但这适用于文件的其余部分,您不能只在包含的文件中使用它。因此,它不能提供完美的范围,可能需要对头文件进行一些重新洗牌/间接包含。

(但坦率地说,如果您无法将头文件修复为符合标准,则不妨整个标头视为system_header,这会将其排除在生成大多数警告之外。

见 https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html

你可以尝试使用它:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvariadic-macros"
#define FOO(A, ...) foo(A, ##__VA_ARGS__)
#pragma GCC diagnostic pop