Selectively disable GCC warnings for only part of a translation unit?

爷,独闯天下 提交于 2019-11-26 00:47:52

问题


What\'s the closest GCC equivalent to this MSVC preprocessor code?

#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.

We have code in commonly included headers which we do not want to generate a specific warning. However we want files which include those headers to continue to generate that warning (if the project has that warning enabled).


回答1:


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 */



回答2:


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.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/965093/selectively-disable-gcc-warnings-for-only-part-of-a-translation-unit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!