|
|
|
|
|
|
Avoiding Multiple Inclusion of Header Files |
|
|
|
|
|
|
|
|
|
The TimeType specification file contains the preprocessor directive #include bool.h. To avoid typing the lines |
|
|
|
|
|
|
|
|
|
typedef int Boolean;
const Boolean TRUE = 1;
const Boolean FALSE = 0; |
|
|
|
|
|
|
|
|
|
in every file that uses Boolean data, we have said that it's useful to put these three lines into a file named bool.h and then #include the file whenever required. But think about what happens if a programmer using the TimeType class already has included bool.h for other purposes, overlooking the fact that timetype.h also includes it: |
|
|
|
|
|
|
|
|
|
#include bool.h
#include timetype.h |
|
|
|
|
|
|
|
|
|
The preprocessor inserts the file bool.h, then timetype.h, and then bool.h a second time (because timetype.h also includes bool.h). The result is a compile-time error, because the identifiers TRUE and FALSE are defined twice. |
|
|
|
|
|
|
|
|
|
The widely used solution to this problem is to write bool.h this way: |
|
|
|
|
|
|
|
|
|
#ifndef BOOL_H
#define BOOL_H
typedef int Boolean;
const Boolean TRUE = 1;
const Boolean FALSE = 0;
#endif |
|
|
|
|
|
|
|
|
|
The lines beginning with # are directives to the preprocessor. BOOL_H(or any identifier you wish to use) is a preprocessor identifier, not a C++ program identifier. In effect, these directives say: |
|
|
|
|
|
|
|
|
|
If the preprocessor identifier BOOL_H is not already defined, then: |
|
|
|
|
|
|
|
|
|
1. define BOOL_H as an identifier known to the preprocessor, and |
|
|
|
|
|
|
|
|
|
2. let the typedef and const declarations pass through to the compiler. |
|
|
|
|
|
|
|
|
|
If a subsequent #includebool.h is encountered, the test #ifndef BOOL_H will fail. The typedef and const declarations will not pass through to the compiler a second time. |
|
|
|
|