A standard for header files
In each header file that contains a
structure, you should first check to see if this header has already been
included in this particular cpp file. You do this by testing a
preprocessor flag. If the flag isn’t set, the file wasn’t included
and you should set the flag (so the structure can’t get re-declared) and
declare the structure. If the flag was set then that type has already been
declared so you should just ignore the code that declares it. Here’s how
the header file should look:
#ifndef HEADER_FLAG
#define HEADER_FLAG
// Type declaration here...
#endif // HEADER_FLAG
As you can see, the first time the header
file is included, the contents of the header file (including your type
declaration) will be included by the preprocessor. All the subsequent times it
is included – in a single compilation unit – the type declaration
will be ignored. The name HEADER_FLAG can be any unique name, but a reliable
standard to follow is to capitalize the name of the header file and replace
periods with underscores (leading underscores, however, are reserved for system
names). Here’s an example:
//: C04:Simple.h
// Simple header that prevents re-definition
#ifndef SIMPLE_H
#define SIMPLE_H
struct Simple {
int i,j,k;
initialize() { i = j = k = 0; }
};
#endif // SIMPLE_H ///:~
Although the SIMPLE_H after the
#endif is commented out and thus ignored by the preprocessor, it is
useful for documentation.
These preprocessor statements that
prevent multiple inclusion are often referred to as include
guards.