Short answer
A .h file is a header file: a text file of C or C++ code that holds declarations, macros and type definitions. Other source files bring its contents in with an #include line. The .h ending is a naming convention, and the compiler does not require it.
What goes in a header
Typical contents include:
- function prototypes, which are declarations without bodies
struct,classandenumdefinitions- macros and constants
- type aliases, written with
typedeforusing - inline functions and templates, which need their full code visible wherever they are used
Ordinary function bodies and global variables usually go in a .c or .cpp file instead.
An example
// shapes.h
#ifndef SHAPES_H
#define SHAPES_H
struct Point {
double x;
double y;
};
double distance_between(Point a, Point b);
#endif // SHAPES_H
The matching source file provides the body:
// shapes.cpp
#include <cmath>
#include "shapes.h"
double distance_between(Point a, Point b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
return std::sqrt(dx * dx + dy * dy);
}
In C, you would write struct Point each time you use the type, because C requires the keyword. C++ lets you use Point on its own.
Including a .h file
#include "shapes.h"
Quotes are for project headers. Standard library headers use angle brackets. Standard C++ headers such as <vector> have no extension at all. The C library headers keep the .h form, such as <stdio.h>, and C++ also provides versions without it, such as <cstdio>.
Other extensions
Compilers do not care which extension you pick, so the choice comes down to your team’s convention:
.his common for C headers and is also used in C++ projects..hppand.hhare common names for C++ headers..hxxappears in some codebases.
Pick one and use it throughout the project.
Headers and source files
Source files such as .c and .cpp are compiled into object code. A header is normally not compiled on its own. Its contents are pasted into each source file that includes it, and the compiler reads them as part of that file.
One common mistake
If a .h file contains a normal function body, such as int add(int a, int b) { return a + b; }, and two source files include it, the linker reports a multiple definition error when both are linked together. Keep the body in a source file, or mark the function inline.