Why should I always enable compiler warnings?

后端 未结 20 1636
时光说笑
时光说笑 2020-11-22 00:28

I often hear that when compiling C and C++ programs I should \"always enable compiler warnings\". Why is this necessary? How do I do that?

Sometimes I also hear tha

20条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 00:57

    As someone who works with legacy embedded C code, enabling compiler warnings has helped show a lot of weakness and areas to investigate when proposing fixes. In gcc utilizing -Wall and -Wextra and even -Wshadow have become vital. I'm not going to go every single hazard, but I'll list a few that have popped up that helped show code issues.

    Variables being left behind

    This one can easily point to unfinished work and areas that might not be utilizing all of the passed variables which could be an issue. Let's look at a simple function that may trigger this:

    int foo(int a, int b)
    {
       int c = 0;
    
       if (a > 0)
       {
            return a;
       }
       return 0;
    }
    

    Just compiling this without -Wall or -Wextra returns no issues. -Wall will tell you though that c is never used:

    foo.c: In function ‘foo’:

    foo.c:9:20: warning: unused variable ‘c’ [-Wunused-variable]

    -Wextra will also tell you that your parameter b doesn't do anything:

    foo.c: In function ‘foo’:

    foo.c:9:20: warning: unused variable ‘c’ [-Wunused-variable]

    foo.c:7:20: warning: unused parameter ‘b’ [-Wunused-parameter] int foo(int a, int b)

    Global Variable shadowing

    This one bit hard and did not show up until -Wshadow was used. Let's modify the example above to just add, but there just happens to be a global with the same name as a local which causes a lot of confusion when trying to use both.

    int c = 7;
    
    int foo(int a, int b)
    {
       int c = a + b;
       return c;
    }
    

    When -Wshadow was turned on, it's easy to spot this issue.

    foo.c:11:9: warning: declaration of ‘c’ shadows a global declaration [-Wshadow]

    foo.c:1:5: note: shadowed declaration is here

    Format strings

    This doesn't require any extra flags in gcc, but it has still be the source of problems in the past. A simple function trying to print data, but has a formatting error could look like this:

    void foo(const char * str)
    {
        printf("str = %d\n", str);
    }
    

    This doesn't print the string since the formatting flag is wrong and gcc will happily tell you this is probably not what you wanted:

    foo.c: In function ‘foo’:

    foo.c:10:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘const char *’ [-Wformat=]


    These are just three of the many things the compiler can double check for you. There are a lot of others like using an uninitialized variable that others have pointed out.

提交回复
热议问题