If you create a program that uses both a Catand a Dog, you will be in danger of includ-
ing ANIMAL.hpptwice. This generates a compile-time error because it is not legal to
declare a class (Animal) twice, even though the declarations are identical.
You can solve this problem with inclusion guards. At the top of your ANIMALheader file,
you write these lines:
#ifndef ANIMAL_HPP
#define ANIMAL_HPP
... // the whole file goes here
#endif
This says, if you haven’t defined the term ANIMAL_HPP, go ahead and define it now.
Between the #definestatement and the closing #endifare the entire contents of the file.
The first time your program includes this file, it reads the first line and the test evaluates
to true; that is, you have not yet defined ANIMAL_HPP. So, it defines it and then includes
the entire file.
The second time your program includes the ANIMAL.hppfile, it reads the first line and the
test evaluates to false because you have already included ANIMAL.hpp. The preprocessor,
therefore, doesn’t process any lines until it reaches the next #else(in this case, there
isn’t one) or the next #endif(at the end of the file). Thus, it skips the entire contents of
the file, and the class is not declared twice.
The actual name of the defined symbol (ANIMAL_HPP) is not important, although it is cus-
tomary to use the filename in all uppercase with the dot (.) changed to an underscore.
This is purely convention; however, because you won’t be able to give two files the same
name, this convention works.
756 Day 21
It never hurts to use inclusion guards. Often, they will save you hours of
debugging time.
NOTE
Macro Functions ..................................................................................................
The #definedirective can also be used to create macro functions. A macro function is a
symbol created using #definethat takes an argument, much like a function does. The
preprocessor substitutes the substitution string for whatever argument it is given. For
example, you can define the macro TWICEas
#define TWICE(x) ( (x) * 2 )
and then in your code you write
TWICE(4)