/sys/doc/ Documentation archive

ifdef Considered Harmful, or Portability Experience With C News


By Henry Spencer (Zoology Computer Systems, University of Toronto) and Geoff Collyer (Software Tool & Die)

We believe that a C programmer’s impulse to use #ifdef in an attempt at portability is usually a mistake. Portability is generally the result of advance planning rather than trench warfare involving #ifdef. In the course of developing C News on different systems, we evolved various tactics for dealing with differences among systems without producing a welter of #ifdefs at points of difference. We discuss the alternatives to, and occasional proper use of, #ifdef.

Introduction

With UNIX running on many different computers, vaguely UNIX-like systems running on still more, and C running on practically everything, many people are suddenly finding it necessary to port C software from one machine to another. When differences among systems cause trouble, the usual first impulse is to write two different versions of the code–one per system–and use #ifdef to choose the appropriate one. This is usually a mistake.

Simple use of #ifdef works acceptably well when differences are localized and only two versions are present. Unfortunately, as software using this approach is ported to more and more systems, the #ifdefs proliferate, nest, and interlock. After a while, the result is usually an unreadable, unmaintainable mess. Portability without tears requires better advance planning.

When we wrote C News [Coll87a], we put a high priority on portability, since we ran several different systems ourselves, and expected that the software would eventually be used on many more. Planning for future adaptations saved us (and others) from trying to force changes into an uncooperative structure when we later encountered new systems. Porting C News generally involves writing a few small primitives. There have been surprises, but in the course of maintaining and improving the code and its portability, we insisted that the software remain readable and fixable. And we were not prepared to sacrifice performance, since one of C News’s major virtues is that it is far faster than older news software. We evolved several tactics that should be widely applicable.

See also