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 this:
#ifndef FILE_FOO_SEEN #define FILE_FOO_SEEN the entire file #endif /* FILE_FOO_SEEN */
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 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 applications
programmers---to know that a certain header file should only be included
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.
Packaging copyright © 1988-2000 OAR Corporation
Context copyright by each document's author. See Free Software Foundation for information.