How to disable warnings for particular include files?

廉价感情. 提交于 2019-11-27 11:24:55

When using GCC you can use the -isystem flag instead of the -I flag to disable warnings from that location.

So if you’re currently using

gcc -Iparent/path/of/bar …

use

gcc -isystem parent/path/of/bar …

instead. Unfortunately, this isn’t a particularly fine-grained control. I’m not aware of a more targeted mechanism.

A better GCC solution: use #pragma.

#pragma GCC diagnostic push 
#pragma GCC diagnostic ignored "-W<evil-option>"
#include <evil_file>
#pragma GCC diagnostic pop

for example:

#pragma GCC diagnostic push 
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <QtXmlPatterns>
#pragma GCC diagnostic pop

When I use g++ and I have third party headers that generate tons of warnings with my usual defaults of -Wall -Wextra & co. I tend to group them in separate includes, specifying the system_header #pragma.

[...] GCC gives code found in system headers special treatment. All warnings, other than those generated by #warning (see Diagnostics), are suppressed while GCC is processing a system header. Macros defined in a system header are immune to a few warnings wherever they are expanded. This immunity is granted on an ad-hoc basis, when we find that a warning generates lots of false positives because of code in macros defined in system headers.

[...]

There is also a directive, #pragma GCC system_header, which tells GCC to consider the rest of the current include file a system header, no matter where it was found. Code that comes before the #pragma in the file will not be affected. #pragma GCC system_header has no effect in the primary source file.

I prefer this solution to the -isystem one because it's more fine-grained and I can put it directly in the sources, without messing too much with command line arguments and include directories.

Example with the hideous root library:

#ifndef ROOTHEADERS_HPP_INCLUDED
#define ROOTHEADERS_HPP_INCLUDED
#ifdef __GNUC__
// Avoid tons of warnings with root code
#pragma GCC system_header
#endif
#include "TH1F.h"
#include "TApplication.h"
#include "TGraph.h"
#include "TGraph2D.h"
#include "TCanvas.h"
#endif

I guess the simplest solution would be write a simple script that will call the compiler, compile, and strip the undesired output, based on the filename and warning type. You can use different scripts for each compiler.

Just update your makefile to use this script instead of calling the compiler directly.

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