C Header Files and The C Preprocessor
Header files contain information to be shared among several C source files.
The mechanism used for sharing header files is the C preprocessor.
The header files for the standard C library are a good example of header files.
We use a header file by having the C preprocessor include it in our source files.
We very often begin a C source (program) file with:
#include <stdio.h>
The above line of code is an instruction to the preprocessor telling
it to include the stdio.h standard library header file with the source
file it sends to the C compiler.
Most headers contain function prototypes, type definitions, and/or
macro definitions.
As C programmers we can make our own header files for use in our programs.
For example, a header file named boolean.h might contain the following lines:
#define boolean int
#define FALSE 0
#define TRUE !FALSE
Other files can access these macro definitions by using the directive:
#include "boolean.h"
Putting macro definitions in header files has several advantages:
- We don't have to copy the definitions into each source file.
- Changing the definition of a macro requires that we edit only a single header file.
- We don't have to worry about the possibility that different source files might contain different versions of the macro.
Another common kind of header file contains declarations of the functions in
a particular source file. Suppose we have a file demo.c which contains:
int f1(int a, int b) {...} /* for external use */
void f2(float x, int y) {...} /* for external use */
float f3(float x) {...} /* for internal use */
void f4(char c) {...} /* for internal use */
Declarations of f1 and f2 should be put in a header file named demo.h:
int f1(int a, int b);
void f2(float x, int y);
Then demo.h should be included in every file in which f1 or f2 is called.