Friday, January 9, 2009

Compiler warnings

I demand that you can compile your sources without warnings at the highest compiler warning level.
Note that there may exist differences in the number of warnings issued between an non-optimizing compile (cc -O0 ...) and an optimizing compile (cc -O3 ...). Of course both compiles should be satisfied.
Further, extended syntax-check programs such as lint should be used permanently.
The time saved by using the compiler's hints is typically more than the time spent to keep the sources warning-less.
Some third party libraries or even compilation systems(!) may include header files that produce annoying warnings when compiled with the highest warning level. I recommend to encapsulate the offending interface declarations in a code layer that meets the warning-less requirement
If the source code is to be distributed and will be used on a variety of systems, it should be revised for warning-less compile on several compilers and/or computer/operating systems. You may also want to do cross-compiles.
Compiler warnings may be a hint of incompatibilities. E.g. the warning "possible bad alignment" may not be an error on CISC CPU architecture systems, but will be one on RISC systems.
Compiling C code as C++ code may reveal C/C++ incompatibilities15, specially with assignments from and to void*16.

Style warnings
Some compiler warnings reveal bad coding style rather than errors or incompatibilities. These bad styles should be avoided.
The warning "assignment in conditional expression" can be avoided by using while((p = next()) != 0) instead of while(p = next()).
The warning "conditional expression is constant" can be avoided by using for(;;) instead of while(1).
The "unreferenced parameter" warning is a tough one in the C language17. Suggestions were: casting to void (does not suppress the warning on all compilers) and self assignment (looks weird and lets me think of a "statement has no effect" warning).
Asserts (assert.h) may produce "statement has no effect" warnings in the release version. This one seems to be tough.
The "comparison of signed and unsigned values" warning appears if signed and unsigned values are mixed in a less/greater expression. One approach is not to use unsigned values at all. strlen() may unfortunately require an int cast.

0 Comments: