仅对翻译单元的一部分选择性禁用 GCC 警告

与这个 MSVC预处理器代码最接近的 GCC 等价物是什么?

#pragma warning( push )                    // Save the current warning state.
#pragma warning( disable : 4723 )          // C4723: potential divide by 0
// Code which would generate warning 4723.
#pragma warning( pop )                     // Restore warnings to previous state.

我们在通常包含的头中有代码,我们不想为其生成特定的警告。但是,我们希望包含这些头的文件继续生成该警告(如果项目启用了该警告)。

56171 次浏览

The closest thing is the GCC diagnostic pragma, #pragma GCC diagnostic [warning|error|ignored] "-Wwhatever". It isn't very close to what you want, and see the link for details and caveats.

I've done something similar. For third-party code, I didn't want to see any warnings at all. So, rather than specify -I/path/to/libfoo/include, I used -isystem /path/to/libfoo/include. This makes the compiler treat those header files as "system headers" for the purpose of warnings, and so long as you don't enable -Wsystem-headers, you're mostly safe. I've still seen a few warnings leak out of there, but it cuts down on most of the junk.

Note that this only helps you if you can isolate the offending code by include-directory. If it's just a subset of your own project, or intermixed with other code, you're out of luck.

This is possible in GCC since version 4.6, or around June 2010 in the trunk.

Here's an example:

#pragma GCC diagnostic push
#pragma GCC diagnostic error "-Wuninitialized"
foo(a);         /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
foo(b);         /* no diagnostic for this one */
#pragma GCC diagnostic pop
foo(c);         /* error is given for this one */
#pragma GCC diagnostic pop
foo(d);         /* depends on command line options */

This is an expansion to Matt Joiner's answer.

If you don't want to spawn pragmas all over your code, you can use the _Pragma operator:

#ifdef __GNUC__
#  define DIAGNOSTIC_ERROR(w) _Pragma("GCC diagnostic error \"" w "\"")
#  define DIAGNOSTIC_IGNORE(w) _Pragma("GCC diagnostic ignore \"" w "\"")
#  define DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
#  define DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
#endif
// (...)


DIAGNOSTIC_ERROR("-Wuninitialized")
foo(a); // Error


DIAGNOSTIC_PUSH
DIAGNOSTIC_IGNORE("-Wuninitialized")
foo(a); // No error


DIAGNOSTIC_POP
foo(a); // Error