Search code examples
cgcccode-analysiscompiler-warningscompiler-flags

Disadvantages of using the `-Wextra` flag when compiling in GCC


I know that one should always compile with both -Wall and -Wextra as they enable warnings and help us to understand our mistake, if any.

I've read that the -Wextra compiler flag is not recommended to use because it is too verbose with a lot of false positives.

I was quite surprised on reading this. So I started googling about it but I didn't get any answer as all the search results showed was "what does the -Wextra flag do?".

So, my questions are

  • In which all situations does the -Wextra flag emit uneccessary warnings?
  • Is it possible to stop the -Wextra flag from enabling the other flags that cause GCC from emitting these types of warnings?

Solution

  • The point about the usefulness of -Wextra warnings is that the corresponding warnings have these properties (more or less):

    1. They generate false positives.

    2. The false positives are relatively frequent.

    3. Adapting the code to avoid false positives is a nuisance.

    The consequence is, that many projects that switch on -Wall -Wextra give up trying to avoid all the warnings. Consequently, when you compile such a project, you see hundreds and hundreds of warnings, almost all about legit code. And the one warning that you should have seen slips unnoticed in the endless warning stream. Worse: the fact that a normal compilation spits out so many warnings makes you get sloppy about avoiding the new warnings that your new code introduces. Once a project reaches a few tens of warnings, the fight is usually over; it will require a heroic effort to bring the warning count back to zero.

    Here is an example of some perfectly legitimate code that is barked at by -Wextra:

    void myClass_destruct(MyClass* me) {}
    

    It's a destructor and it's empty. Yet, it should be there simply to facilitate calling it at the appropriate points (subclass destructors), so that it is easy to add stuff to MyClass that needs cleanup. However, -Wextra will bark at the unused me parameter. This forces programmers to write code like this:

    void myClass_destruct(MyClass* me) {
        (void)me;    //shut up the compiler barking about the unused parameter
    }
    

    This is plain noise. And it gets annoying to write such code. However, in order to achieve a zero warning count under a -Wextra regime, this noise needs to be added to the code. So, you can pick any two of these three:

    1. Clean code

    2. Zero warning count

    3. -Wextra warnings

    Choose wisely which one you want to drop, you won't get all three.