f78 Once-Only Include Files Contents|Index|Previous|Next
 

Once-only include files 

Very often, one header file includes another. It can easily result that a certain header file is included more than once. This may lead to errors, if the header file defines structure types or typedefs, and is certainly wasteful. Therefore, we often wish to prevent multiple inclusion of a header file.

The standard way to do this is to enclose the entire real contents of the file in a conditional, like the following.

The macro, FILE_FOO_SEEN, indicates that the file has been included once already. In a user header file, the macro name should not begin with ‘_’. In a system header file, this name should begin with ‘__’ to avoid conflicts with user programs. In any kind of header file, the macro name should contain the name of the file and some additional text, to avoid conflicts with other header files.

The GNU C preprocessor is programmed to notice when a header file uses this particular construct and handle it efficiently. If a header file is contained entirely in a #ifndef conditional, then it records that fact. If a subsequent #include specifies the same file, and the macro in the #ifndef is already defined, then the file is entirely skipped, without even reading it.

There is also an explicit directive to tell the preprocessor that it need not include a file more than once. This is called #pragma once, and was used in addition to the #ifndef conditional around the contents of the header 67c file. #pragma once is now obsolete and should not be used at all.

In the Objective C language, there is a variant of #include called #import which includes a file, but does so at most once. If you use #import instead of #include, then you don’t need the conditionals inside the header file to prevent multiple execution of the contents.

#import is obsolete because it is not a well designed feature. It requires the users of a header file—the application’s programmer’s header file—to know that a certain header file should be included only once. It is much better for the header file’s implementor to write the file so that users don’t need to know this. Using #ifndef accomplishes this goal. 0