Header files should be guarded.
#ifndef H_int_stack
#define H_int_stack
/* body of int_stack.h */
#endif
The name H_int_stack
is the guard for the file; by convention the tag for a file header.h
is H_header
. Any characters such as '-
' are replaced by '_
'.
Guarding header files has two purposes; first, of all ensures that a header file is processed exactly once, even if it is #include
multiple times.
For instance, consider the following code sequence:
/* first include */
#include "int_stack.h"
/* second include */
#include "int_stack.h"
The first include will go through as usual; the full contents of int_stack.h
will be included. During this process, H_int_stack
will be defined. During the second include, the #ifndef
will fail, and the body of int_stack.h
will be skipped.
There are many compilers which use these guards to speed up compilation. It is common for a header file to get included multiple times. The use of guards will prevent the body of the header from getting processed multiple times. However, the header file should logically still be opened and read. To speed up compilation, the compiler will keep track of guarded files, and guard names. If it encounters a file that was guarded, it will skip the step of opening and reading the file.
If you happen to be using a compiler that does not support this optimization, or you may need to port to a system with that kind of compiler, you can still get the same effect by using the following idiom to include headers.
#ifndef H_int_stack
#include "int_stack.h"
#endif
With this idiom, if an header has already been included, the guard will cause the #include
to be skipped, and so the header file will not even be opened.