[comp.lang.c] recursive includes

dmg@ssc-vax.UUCP (David Geary) (03/03/89)

From: samperi@marob.MASA.COM (Dominick Samperi)
Message-ID: <570@marob.MASA.COM>

>Are recursive #includes hazardous to your software's health? 

  No.

>I'm working on a system where each header file has the form:

><contents of foo.h>:

>#ifndef H_FOO
>#define H_FOO

>defines, declarations, etc.

>#endif

  Yes, I do the very same thing.

>This scheme permits header files to be included two or more times, even
>recursively, where the second and subsequent includes of the same file
>will have no effect. (That is, a header file A can include another header
>file B, which in turn includes A, but since H_A will be defined when A
>is included the first time, the second include of A will have no effect,
>and the recursion will end.)

  Yup.  However, not really recursion, because the recursion never happens.

>Although this trick will avoid the common problems caused by including
>a header file more than once, I suspect that it will also encourage
>the inclusion of files that are not even needed (since there is
>no chance for multiple definitions, if there is some chance that the
>definitions may be needed, what the heck). Furthermore, permitting

  I don't see where this would "also encourage the inclusion of files
that are not even needed".  It may very well cause some laziness on
a programmers part by including the same file twice, which really
makes no difference, (except for miniscule amount of time to it takes
to open the file and process #ifndef).

>recursive includes may tend to smear the separation between modular
>components of the software system, and designing a correct makefile
>will be a mess.

  Maybe this would be true if header files are included that are
not needed, but I don't think that's the case (see above). 

>These problems, together with the discovery that some preprocessors
>consider any recursive include to be a fatal error, have motivated me
>to discontinue the use of this trick, and discontinue the use of
>recursive includes as well.

  If a preprocessor does not allow the above construct of:

  #ifndef FLAG
  #define FLAG

  stuff...

  #endif

Then the compiler is broken.  From pages 91 and 92 of K&RV2:

"It is possible to control preprocessing itself with conditional
statements that are evaluated during preprocessing.  This provides
a way to include code selectively, depending on the value of
conditions evaluated during compilation...

  #ifndef  HDR
  #define  HDR

  /* contents of hdr.h go here */

  #endif"

If it's good enough for Dennis Ritchie, it's good enough
for me ;-).

  David Geary



-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ David Geary, Boeing Aerospace,               ~ 
~ #define    Seattle     RAIN                  ~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~