Short answer
The main purpose of a header is to declare things in one place so that many source files can use them. A source file that calls a function needs to know its name, return type and parameters. The header provides that information, while the function’s code lives in another file.
Why the compiler needs declarations
C and C++ compile each source file separately. When the compiler reads main.cpp, it looks at that file and the headers it includes. It does not look inside counter.cpp. Any name used in main.cpp must therefore be declared in that file, and a header is the usual way to do it.
Declaration versus definition
- A declaration says that a thing exists and what it looks like, such as
int next_id();. - A definition provides the actual code or storage, such as
int next_id() { ... }.
Headers usually hold declarations, and source files usually hold definitions. There are exceptions, such as inline functions, templates and constants, which often appear in headers.
An example
The header declares the function:
// counter.h
#ifndef COUNTER_H
#define COUNTER_H
int next_id();
#endif // COUNTER_H
The source file defines it:
// counter.cpp
#include "counter.h"
int next_id() {
static int last_id = 0;
return ++last_id;
}
The main program uses it by including the same header:
// main.cpp
#include <iostream>
#include "counter.h"
int main() {
std::cout << next_id() << '\n';
std::cout << next_id() << '\n';
return 0;
}
The output is:
1
2
Any other file that includes counter.h can call next_id() the same way, without a copy of its code.
What the header buys you
- Each source file compiles on its own. Editing
counter.cpponly requires recompiling that file, and then relinking. - The interface lives in one place. If a signature changes, you update the header and recompile the files that include it.
- The compiler can check that calls and definitions match the declarations.
The cost
A header’s text is pasted into every file that includes it. Editing a widely included header therefore means recompiling all of those files. This is one reason to keep headers small and to leave function bodies in source files.