Finer gcc -Wshadow Option Behavior

People, I really like the -Wshadow option, as it helps to identify some possible problematic code fragments. I want to use it in a really big project, but I can’t because it is too strict. For example, it issues a warning for the following case:

struct Foo { Foo(int info) : info_(info) {} //shadow warning is here void info(){ ... } int info_; }; 

gcc issues a warning about the "int info" method for the "int info" variable in the constructor, which ... well, actually this is not a very useful warning for me.

I really like cases like:

  int i = 0; for(int j=0;j<10;++j) { int i = j; //local scope variable "int i" shadows outer scope variable ++i; } 

Can gcc be warned only about these cases?

+7
c gcc
source share
2 answers

For external libraries, you can try specifying your include path with -isystem instead of -I , this will cause gcc to stop reporting warnings to them often.

When a warning appears only in a few limited cases, you can bypass it with:

#pragma GCC diagnostic ignored "-Wshadow"

Otherwise, code refactoring or the grep trick Peter talked about seems to be the only options.

+10
source share

Unfortunately, gcc does not have the ability to disable warnings for specific lines. In any case, if you do this, you should simply rename your constructor info parameter to my_info and the shadow will disappear.

The best advice I can give you is to work on removing all of these warnings, even if you don’t care. In general, it is best not to use parameter names that hide member functions.

This is the approach we took to incorporate new warnings and introduce other static checkers. In my opinion, pain generally wins.

In some cases, we managed to run the script by code to make changes for us. I'm not sure how easy it is. Alternatively, a good editor (such as emacs or VIM) should help you make this type of “mechanical” change semi-automatically and fairly quickly if you can manage the editor well!

Another really hacky option is to create a list of known “good” exceptions and to deduce them from the compiler output. You can create a wrapper for gcc that simply extracts warnings you don't want to see. I do not recommend it, it may be easier to fix your code base!

+3
source share

All Articles