Fri, 04 Jan 2008

#ifdef and -Wundef

One of the problems with the C preprocessor is that it deals with undefined symbols by treating them as 0, which can hide bugs. A subtler problem is the widespread use of #ifdef: if you make a typo or use an obsolete name, you don't get any warning.

Fortunately, gcc has -Wundef, which warns about any undefined preprocessor symbols. But to use it to its full effect, you need to change the common C idiom of ifdefs. Instead of this:

/* Define HAVE_FOO if you have foo support. */
#ifdef HAVE_FOO

You need to start doing this:

/* Define HAVE_FOO to 1 if you have foo support, otherwise 0. */

The fact that the Linux kernel uses #ifdefs instead of #if and -Wundef is one of those warts which would be nice to fix if we were starting over, but not worth the churn for such an established project. New projects however...

[/tech] permanent link