Since header files are made up of syntactically correct C and C++ ASCII text, and are included in other files at the point of the #include directive, many beginning programmers misuse them. Sometimes they are incorrectly used to define entire functions or collections of functions. While this approach does not invoke any complaints from the compiler, it is a logical misuse of the structure.
Header files are used to define and share common declarations with several source files. They provide a centralized location for the declaration of all external variables, function prototypes, class definitions, and inline functions. Files that must declare a variable, function, or class #include header files.
This provides two safeguards. First, all files are guaranteed to contain the same declarations. Second, should a declaration require updating, only one change to the header file need be made. The possibility of failing to update the declaration in a particular file is removed. Header files are frequently made up of the following:
•
const declarations
•
enumerated types
•
function prototypes
•
preprocessor directives
•
references to externs
•
structure definitions
•
typedefs
Caution should be exercised when designing header files. The declarations provided should logically belong together. A header file takes time to compile. If it is too large or filled with too many disparate elements, programmers will be reluctant to incur the compile-time cost of including them.
A second consideration is that a header file should never contain a nonstatic definition. If two files in the same program include a header file with an external definition, most link editors will reject the program because of symbols defined multiple times. Because constant values are often required in header files, the default linkage of a const identifier is static. For this reason, constants can be defined inside header files.