How to disable warnings for particular include files?
I wold like to disable particular warnings for all files that are included, directly or indirectly, by particular include files. For example, I want to disable the warning "you are assigning a string literal to a char*", for all files or files included by files included by a #include <bar/*>
(the star in my case means "anything may be here").
The reason is, some of the people I have to program with just can't use "const", so in the end I get lots of warnings about that particular string literal abuse. I would like to ignore those thousands of warnings coming from their code, so I can concentrate on the mistakes in my own code and fix them.
I use Intel C++ and GCC. Some of my buddies use clang, so I would be glad to hear solutions for that too.
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