A solution to the multiple inclusion problem

Lawrence Crowl crowl at cs.rochester.edu
Tue Oct 24 05:16:34 AEST 1989


In article <14240 at well.UUCP> nagle at well.UUCP (John Nagle) notes three
solutions to the multiple file inclusion problem:

(1) An include file protects itself via #ifndef on a symbol that it defines.
    This causes the file to be read multiple times.

(2) Modifying the semantics of #include to only include a file once.  This is
    incompatible with the current definition of #include.

(3) His proposal for modifying the implementation of #include to recognize the
    idiom in (1).  Implementations need not read a file twice.

However, a solution to the multiple inclusion problem already exists.  It is
not necessary (nor desireable in my opinion) to modify #include semantics or
implementations.  The solution is as follows.

Each include file defines a symbol (preferably related to its name).  For
example, in foo.h:

        #define foo_h
        ...

Each file that includes foo.h, protects the inclusion with a #ifndef:

        ...
        #ifndef foo_h
        #include "foo.h"
        #endif foo_h
        ...

Programmers of include files can further protect against multiple inclusion
by using the standard mechanism:

        #ifndef foo_h
        #define foo_h 
        ...
        #endif foo_h

This solution has the following properties:
- The compiler reads include files exactly once.
- No modifications to current systems are required.
- Includes are three lines long instead of one.
- A small (really) amount of additional programmer effort is required.

I have used this solution as a matter of course since shortly after I learned
to program in C.  It is an obvious solution, and leads me to wonder why it is
not common practice.  Any explainations?
-- 
  Lawrence Crowl		716-275-9499	University of Rochester
		      crowl at cs.rochester.edu	Computer Science Department
...!{allegra,decvax,rutgers}!rochester!crowl	Rochester, New York,  14627



More information about the Comp.lang.c mailing list