As C programs become larger, putting everything in a single file becomes difficult.
C provides header files to store declarations, macros, and other information that can be shared between different source files.
What is a Header File?
A header file is a file, usually with a .h extension, that contains declarations and other information that can be included in C source files.
For example:
#include <stdio.h>
Here, stdio.h is a standard header file.
It provides declarations for functions such as printf() and scanf().
Types of Header Files
Header files are generally of two types:
1. Standard Header Files
These are provided by the C standard library.
Some common examples are:
Header File | Common Use |
|---|---|
| Input and output |
| Memory allocation, conversions, utilities |
| String operations |
| Mathematical functions |
| Character checking and conversion |
| Date and time |
For example:
#include <string.h>
allows us to use functions such as strlen() and strcpy().
2. User-Defined Header Files
We can also create our own header files.
Suppose we create:
mathutils.h
It could contain a function declaration:
int add(int a, int b);
Then another C file can include it:
#include "mathutils.h"
Notice the difference:
#include <stdio.h> // Standard header
#include "mathutils.h" // User-defined header
Why Use Header Files?
Header files are useful because they allow us to:
Organize large programs
Share function declarations
Share macros and types
Separate interfaces from implementations
Reuse common declarations across multiple source files
For example, a large project might look like:
Project
├── main.c
├── calculator.c
├── calculator.h
├── student.c
└── student.h
This makes the project much easier to manage.
Header Files and #include
We include a header file using the #include preprocessor directive:
#include <stdio.h>
The preprocessor processes this directive before compilation so that the declarations and other contents from the header are available to the source file.
Header Guards
When creating your own header files, you may see header guards:
#ifndef MATHUTILS_H
#define MATHUTILS_H
int add(int a, int b);
#endif
They help prevent the contents of a header from being processed multiple times in the same compilation unit.
Modern C projects may also use #pragma once, although it is not part of the ISO C standard.
In Simple Words
A header file contains declarations and other reusable information that can be shared across C source files.
For example:
#include <stdio.h>
allows us to use declarations from the standard input/output library.
Header files become especially important when building large, modular C programs with multiple source files.