tags:

views:

365

answers:

2

Folks, I really like the -Wshadow option since it helps to spot some possible problematic pieces of code. I want to use it in a really large project but I can't since it's too strict. For example it throws a warning for the following case:

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

gcc throws a warning about "int info" variable shadowing "void info" method in constructor which is... well, not really a useful warning for me.

What I really care about is cases such as the following:

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

Is it possible to make gcc warn about these cases only?

+1  A: 

Sadly gcc has no way to disable warnings for specific lines. Anyway, if you were doing that, you should just rename your constructor's info parameter to my_info, and the shadow will go away.

The best advice I can give you is to work on removing all those warnings, even though you don't care about them. In general it is better to not use parameter names that hide member functions.

This is the approach we have taken in enabling new warnings, and introducing other static checkers. In my opinion the pain is worth the gain overall.

For some cases we were able to run a script over the code to make the changes for us. I'm not sure how easy that would be. Alternatively a good editor (such as emacs or VIM) should help you make that type of "mechanical" change semi-automatically and fairly quickly, if you can drive the editor well!

One other really hacky option is to create a list of known "okay" exceptions, and grep them out of the compiler output. You could create a wrapper for gcc, which would just extract warnings you don't want to see. I don't recommend it though, it's probably be easier to fix your code base!

Peter
We are using lots of external libraries(e.g boost) and patching them is not an option....
pachanga
If you are building external code, your best choice is to change your compile flags in the directory that contains (only) external code. You can either remove the warning causing you problems, or prevent warnings from being errors.
Peter
Could you please give a link or describe a way how to do this? What if the library is "headers only"?
pachanga
+2  A: 

For external libraries you can try to specify their include path with -isystem instead of -I, this will cause gcc to stop reporting warnings in them most of the time.

When the warning only pops up in a few limited cases you can work around it with:

#pragma GCC diagnostic ignored "-Wshadow"

For the rest of the cases refactoring the code or doing the grep trick Peter mentioned seem to be the only options.

Grumbel
Oh, many thanks, I'll have a closer look at "-i" option and #pragma
pachanga