Page 126 - C-Language
P. 126

Recommendation: Header files should be self-contained.





        Historical rules


        Historically, this has been a mildly contentious subject.

        Once upon another millennium, the AT&T Indian Hill C Style and Coding Standards stated:


              Header files should not be nested. The prologue for a header file should, therefore,
              describe what other headers need to be #included for the header to be functional. In
              extreme cases, where a large number of header files are to be included in several
              different source files, it is acceptable to put all common #includes in one include file.

        This is the antithesis of self-containment.


        Modern rules


        However, since then, opinion has tended in the opposite direction. If a source file needs to use the
        facilities declared by a header header.h, the programmer should be able to write:


         #include "header.h"


        and (subject only to having the correct search paths set on the command line), any necessary pre-
        requisite headers will be included by header.h without needing any further headers added to the
        source file.


        This provides better modularity for the source code. It also protects the source from the "guess
        why this header was added" conundrum that arises after the code has been modified and hacked
        for a decade or two.

        The NASA Goddard Space Flight Center (GSFC) coding standards for C is one of the more
        modern standards — but is now a little hard to track down. It states that headers should be self-
        contained. It also provides a simple way to ensure that headers are self-contained: the
        implementation file for the header should include the header as the first header. If it is not self-
        contained, that code will not compile.

        The rationale given by GSFC includes:


              §2.1.1 Header include rationale


              This standard requires a unit’s header to contain #include statements for all other
              headers required by the unit header. Placing #include for the unit header first in the unit
              body allows the compiler to verify that the header contains all required #include
              statements.

              An alternate design, not permitted by this standard, allows no #include statements in
              headers; all #includes are done in the body files. Unit header files then must contain



        https://riptutorial.com/                                                                             102
   121   122   123   124   125   126   127   128   129   130   131