A header file exists to communicate type information from one programming unit (file or library) to another
This information includes:
- function declarations (most importantly)
- structure definitions
- global variables (to be avoided)
- preprocessor macros and definitions
including headers
Header files are included in C source files and in other header files by preprocessor commands. Two notations distinguish where the compiler searches for the header file.
#include <filename.h> /* searches compiler-defined path */ #include "filename.h" /* searches current directory */The result is just as if the contents of the header file replaced the
include
statement textually.
Note: the “compiler-defined” path can be extended by a command-line flag (-I) of the compiler command.
dangers
Unless you are systematic about header inclusion, header mayhem will result.
Examples: multiply-declared symbols, long compile times, and a great deal of time lost worrying about the correct order of header inclusion.
best practices
I strongly recommend that each header
- include exactly the other headers needed to describe its contents
- have an include guard.
This way, the order of header inclusion doesn’t matter, and small changes in headers are least likely to result in problems with other files.
An otherwise empty source file that just includes the header should compile.