← All Posts

C++ Header Files

What Is a Header File?

A header file is a shared declaration file. It tells other .cpp files that a type, function, constant, or template exists. The header usually does not own the main implementation. It describes the interface that other source files can compile against.

A Minimal Header

// include/math_demo/vector2.h #pragma once namespace math_demo { class Vector2 { public: Vector2(double x, double y); double x() const; double y() const; double length() const; private: double x_; double y_; }; } // namespace math_demo

This header declares a class. It says which constructors and member functions exist, but the function bodies can live in vector2.cpp.

What Belongs in a Header?

Put in headersAvoid in headers unless needed
Class declarationsLarge function bodies
Function declarationsNon-inline global variable definitions
Small inline functionsHeavy includes that only the .cpp file needs
Templates, because their definitions must be visibleAnonymous namespaces
Constants intended for users of the APIPrivate helper functions that only one source file uses

Include Guards and #pragma once

A header can be included more than once in the same translation unit through nested includes. Protection is mandatory.

The simple modern style:

#pragma once

The portable traditional style:

#ifndef MATH_DEMO_VECTOR2_H #define MATH_DEMO_VECTOR2_H // declarations #endif // MATH_DEMO_VECTOR2_H

Forward Declarations

If a header only stores a pointer or reference to a type, it often does not need the full definition. A forward declaration can reduce compile-time dependencies.

// renderer.h #pragma once class Texture; // forward declaration class Renderer { public: void draw(const Texture& texture); };

The full Texture definition can be included in renderer.cpp, where the function body actually needs it.

A Bad Header Pattern

// bad.h #pragma once #include <vector> #include <map> #include <iostream> int global_counter = 0; // bad: definition in a header void helper() { // bad unless inline: definition in a header std::cout << "help\\n"; }

If this header is included by multiple .cpp files, the linker may see multiple definitions of global_counter and helper. That is why headers must be designed carefully.

What Comes Next

Headers declare the interface. Source files provide the implementation.