Wednesday, March 21, 2012

Convert warnings to error with GCC

What happens if you execute below code?

int i = 10;
printf("%s Bad format specifier\n", i);


nandakumar@HERAMBA ~ $ gcc format.c
format.c: In function ‘main’:
format.c:6:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]


Output: Segmentation fault

This is common mistake programmer does. Here printf de-references address location 10 and print out the string value at that address. However 10 is not valid address in the address space and hence the program results in seg fault. GCC also warns about invalid format. However programmers tend to ignore the warnings too often and when errors do happen lot of time is spent to debug the error. The warnings are taken into consideration in above condition since program is too small. However, while working on larger projects, programmers tend to overlook on warnings.

There are two solutions though:

1) Program neatly
2) Find the error during compilation time itself

The first seems to be the ideal solution. However mistakes do happen. The second can be achieved using GCC options. GCC provides compiler switch '-Werror' to convert all warnings to errors. You can even have specific warnings to be shown as errors. For example, in above case we can only use '-Werror=format' to make format warning as error. This greatly helps you to reduce errors even.

How does modified output look like now?

nandakumar@HERAMBA ~ $ gcc -Werror format.c
format.c: In function ‘main’:
format.c:6:2: error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Werror=format]
cc1: all warnings being treated as errors


Now we can see the change! There is an error in program which makes our life easy. That is it for now. Leave comments if you have extra suggestions.