When a large C program is split over several modules, code in one module might need to make references to named code in another, or two modules might need to refer to the same type declaration consistently. The usual way to achieve these is to precede the reference with a declaration that shows what the name means. Some example declarations:
/* This declares the typestruct point
. */ struct point { int x, y; }; /* This declares the global variableerrno
. */ extern int errno; /* this declares the functiongetchar
. */ int getchar(void);
It would be tedious to repeat such declarations in
each source file that requires them, particularly if they
need to be modified as the program develops. Instead,
these could be placed in a separate file (usually with a
.h extension), and inserted automatically by
the preprocessor when it encounters an #include
directive
embedded in the source code, for example:
#include "mydecls.h"
These header files are also preprocessed,
and so may contain further #include
(or other)
directives.
Header files containing declarations for the standard
library are also available to the preprocessor. These are
normally accessed with a variant of the #include
directive:
/* Include declarations for input/output routines. */ #include <stdio.h>
You should normally use the ""
form for your own headers rather than
<>
.
Do not put definitions of functions or variables in header files — it may result in multiple definitions of the same name within one program, so linking will fail. Header files should normally only contain types, function prototypes, variable declarations, and macro definitions. Note that inline functions are exceptional.