Header Files in C
Header Files in C
A header file is a file with the extension .h that contains:
-
C function declarations
-
Macro definitions
-
Shared constants and variables
These are used to share code between multiple source files.
Types of Header Files
There are two types of header files:
-
System Header Files
-
Provided with the compiler
-
Example:
stdio.h
-
-
User-Defined Header Files
-
Written by the programmer
-
Used to organize project-specific declarations
-
Including a Header File
You can include a header file using the C preprocessor directive:
Including a header file is equivalent to copying its contents into your source file.
However, manually copying code is:
-
Error-prone
-
Hard to maintain
-
Not recommended, especially for multi-file programs
Common Practice
A standard practice in C is to store the following in header files:
-
Constants
-
Macros
-
System-wide global variables
-
Function prototypes
Then include that header file wherever needed.
Include Syntax
Both system and user header files use #include, but in different forms.
1. System Header Files
-
Searches for the file in standard system directories
-
You can add directories using the
-Icompiler option
2. User-Defined Header Files
-
Searches first in the current source file directory
-
Then in other include directories
-
You can add directories using the
-Icompiler option
Once-Only Headers (Header Guards)
If a header file is included more than once, the compiler may process it multiple times, causing errors.
To prevent this, use header guards:
How It Works
-
The first time the file is included,
HEADER_FILEis not defined, so the contents are included. -
The macro is then defined.
-
If included again, the condition becomes false, and the file contents are skipped.
This technique is called a wrapper #ifndef or header guard.
Comments
Post a Comment