Header vs source
A header file publishes what a component offers — the declarations other code needs to compile against. A source file supplies the bodies. Splitting them keeps rebuilds small and keeps the one-definition rule satisfied.
Detailed Explanation
The split rests on one distinction. A declaration introduces a name and its type: int countErrors(const std::string&);. A definition supplies the substance: the function body, the storage for a variable, the members of a class. A name may be declared any number of times but defined once (per program for functions and variables, per translation unit for classes and templates).
Headers carry declarations. Source files carry definitions. Consider a session cache in a web backend. SessionCache.hpp declares the class, its member function signatures, and any free functions callers need. SessionCache.cpp defines those functions, plus whatever private helpers only it uses.
What goes where:
| Put in the header | Put in the source |
|---|---|
| Class definitions, enums, type aliases | Member function bodies |
| Function declarations | Free function bodies |
| Templates (definitions included) | Static data member definitions |
constexpr and inline variables | File-local helpers, anonymous namespaces |
| Small accessors worth inlining | Everything else, including #includes only the bodies need |
Three reasons this matters.
The one-definition rule. A non-inline function defined in a header is defined once in every translation unit that includes it, and the linker rejects the duplicates. Anything genuinely defined in a header must be inline, constexpr, a template, or a class member defined inside the class body (which is implicitly inline).
Compile time. A header is reparsed by every file that includes it, and by every file that includes a file that includes it. Add #include <regex> to a widely-included header and you have added several thousand lines of template code to hundreds of translation units. Put that include in the .cpp where the regex is actually used and the cost is paid once.
Rebuild cascades. Build systems rebuild a source file whenever any header it transitively includes changes. Adding one private member to a widely-included class recompiles half the project, even though nothing about the public interface moved. Change a .cpp and you recompile one file. This is why a header should expose the smallest possible surface, and why the Pimpl idiom exists: hide the members behind a pointer so the header stops changing.
Templates break the rule, and it is not an arbitrary exception. A template is not code; it is instructions for generating code. Nothing is compiled until a specific instantiation like Cache<std::string> is requested, and that request happens in the caller's translation unit, which must therefore see the full definition. Put a template's body in a .cpp and every other file gets an undefined reference. The escape hatch is explicit instantiation in the .cpp when you know the small, fixed set of types in advance.
Forward declarations cut dependencies. If your header only mentions class Connection* or Connection& — as a member pointer, a parameter, or a return type — the compiler does not need the class layout, only the promise that the name is a class. Writing class Connection; instead of #include "Connection.hpp" removes an edge from your dependency graph. You need the full definition once you store a Connection by value, inherit from it, call a member on it, or ask for its size.
Code Examples
SessionCache.hpp — interface only. Note what is NOT included here.
// SessionCache.hpp — interface only. Note what is NOT included here.
#pragma once
#include <cstddef>
#include <string>
class Connection; // forward declaration: no #include "Connection.hpp" needed
class SessionCache {
public:
explicit SessionCache(std::size_t capacity);
bool contains(const std::string& id) const; // declared, defined in the .cpp
std::size_t size() const { return count_; } // in-class definition is implicitly inline
void attach(Connection& c); // a reference needs no full type
private:
std::size_t capacity_;
std::size_t count_ = 0;
};SessionCache.cpp — heavy includes live here, paid for once.
// SessionCache.cpp — heavy includes live here, paid for once.
#include "SessionCache.hpp"
#include "Connection.hpp" // now we call members, so the full type is required
#include <unordered_map>
#include <regex>
namespace {
std::unordered_map<std::string, int> store; // helper, invisible outside this file
const std::regex idPattern{R"([a-f0-9]{32})"};
}
SessionCache::SessionCache(std::size_t capacity) : capacity_(capacity) {}
bool SessionCache::contains(const std::string& id) const {
if (!std::regex_match(id, idPattern)) return false;
return store.find(id) != store.end();
}
void SessionCache::attach(Connection& c) { c.keepAlive(); }Common Gotchas
Defining a free function in a header without `inline`
the second translation unit that includes it triggers a duplicate symbol error at link time. Member functions written inside the class body are exempt because they are implicitly inline.
Headers must include what they use
if `SessionCache.hpp` uses `std::string` it must include `<string>` itself, not rely on some other header happening to pull it in first. Otherwise the build breaks the day someone reorders includes in an unrelated file.
Templates in a `.cpp` give link errors, not compile errors
the template file compiles fine on its own, so the failure surfaces as an undefined reference from every caller. Move the definition into the header or add explicit instantiations.
Extension names are convention, not language
`.hpp`, `.h`, `.hh`, and `.hxx` are identical to the compiler. Pick one per project; `.hpp` for C++ and `.h` for C-compatible headers is a common split.