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
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.
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)
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
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.