Header Files

To allow programs to be broken up into logical parts, C++ supports what is commonly known as separate compilation.

Proper use of header files can provide two benefits: All files are guaranteed to use the same declaration for a given entity; and should a declaration require change, only the header needs to be updated.

Headers should be used for declarations and not definitions. There are three exceptions, classes, const objects whose value is known at compile time, and inline functions. These entities are defined in headers because the compiler needs their definitions (not just declarations) to generate code.

A common way to make headers safe uses the preprocessor to define a header guard.

To help avoid name clashes, preprocessor variables usually are written in all uppercase letters.

A preprocessor variable has two states: defined or not yet defined. Various preprocessor directives define and test the state of preprocessor variables.
The #define directive takes a name and defines that name as a preprocessor variable.
The #ifndef directive tests whether the specified preprocessor variable has not yet been defined. If it hasn't, then everything following the #ifndef is processed up to the next #endif.

We can use these facilities to guard against including a header more than once:

Example 1

     #ifndef SALESITEM_H
     #define SALESITEM_H
     // Definition of Sales_item class and related functions goes here
     #endif
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.