TExcelTAD

Forward Declarations, Pimpl & IWYU

PCH and unity builds make heavy includes cheaper. The other approach is to include less. Every #include in a header is paid by every file that includes that header, and becomes a rebuild trigger for all of them. Three tools keep headers lean: forward declarations, the Pimpl idiom, and include-what-you-use.

Forward declarations

A header only needs a type's full definition when it uses the type's size or members: a by-value member, a base class, an inline function body that calls a method. For pointers, references, and function parameters and return types in declarations, a forward declaration is enough:

cpp
// scene.hpp, before
#include "texture.hpp"          // drags in everything texture.hpp includes
struct Scene { Texture* sky; void draw(const Texture& t); };

// scene.hpp, after
class Texture;                  // "Texture is a class", nothing more
struct Scene { Texture* sky; void draw(const Texture& t); };

Only scene.cpp, which calls Texture's members, includes texture.hpp.

This session measures both versions in a project where six files include scene.hpp but only one of them really uses Texture. It counts the preprocessed size of scene.hpp and how many files recompile when texture.hpp changes:

bash · try it yourself
mkdir -p fwd/src && cd fwd
cat > src/texture.hpp <<'H'
#pragma once
#include <map>
#include <string>
#include <vector>
class Texture {
public:
  std::string name;
  std::vector<unsigned char> pixels;
  std::map<std::string, int> tags;
  int width() const { return 4; }
};
H
cat > src/scene-heavy.hpp <<'H'
#pragma once
#include "texture.hpp"
struct Scene { Texture* sky = nullptr; int draw(const Texture& t); };
H
cat > src/scene-light.hpp <<'H'
#pragma once
class Texture;
struct Scene { Texture* sky = nullptr; int draw(const Texture& t); };
H
printf '#include "scene.hpp"\n#include "texture.hpp"\nint Scene::draw(const Texture& t) { return t.width(); }\n' > src/scene.cpp
for n in input audio ai net ui; do printf '#include "scene.hpp"\nint %s(Scene& s) { return s.sky == nullptr; }\n' $n > src/$n.cpp; done
echo 'int main() { return 0; }' > src/main.cpp
printf 'cmake_minimum_required(VERSION 3.25)\nproject(Fwd CXX)\nfile(GLOB SRCS CONFIGURE_DEPENDS src/*.cpp)\nadd_executable(app ${SRCS})\ntarget_include_directories(app PRIVATE src)\n' > CMakeLists.txt
for v in heavy light; do
  cp src/scene-$v.hpp src/scene.hpp
  lines=$(echo '#include "scene.hpp"' | g++ -std=c++20 -x c++ -I src -E - | wc -l)
  rm -rf build && cmake -S . -B build -G Ninja > /dev/null && cmake --build build > /dev/null
  sleep 1 && touch src/texture.hpp
  echo "$v: scene.hpp expands to $lines lines; editing texture.hpp recompiles $(cmake --build build | grep -c 'Building CXX') files"
done
heavy: scene.hpp expands to 41075 lines; editing texture.hpp recompiles 6 files
light: scene.hpp expands to 11 lines; editing texture.hpp recompiles 1 files

Both measures improve. The preprocessed size of scene.hpp drops from tens of thousands of lines to a handful, and an edit to texture.hpp now recompiles one file instead of six. The second effect is often the bigger win in daily work.

The standard library has a forward-declaration header for streams, <iosfwd>, so a header that only mentions std::ostream& doesn't need <iostream>. You must not forward-declare other standard library types yourself (namespace std { class string; } is undefined behaviour, and std::string is an alias anyway).

Pimpl: hiding members too

Forward declarations can't help when the header needs the members of a class, because the size of a class depends on them. The Pimpl ("pointer to implementation") idiom moves all private members into a struct defined only in the .cpp file:

cpp
// widget.hpp: no <map>, <string>, <vector>, no third-party headers
#include <memory>
class Widget {
public:
  Widget();
  ~Widget();                       // defined in widget.cpp, where Impl is complete
  Widget(Widget&&) noexcept;
  Widget& operator=(Widget&&) noexcept;
  int size() const;
private:
  struct Impl;                     // forward declaration
  std::unique_ptr<Impl> impl_;
};

// widget.cpp
#include "widget.hpp"
#include <map>
#include <string>
struct Widget::Impl { std::map<std::string, int> items; };
Widget::Widget() : impl_(std::make_unique<Impl>()) {}
Widget::~Widget() = default;
Widget::Widget(Widget&&) noexcept = default;
Widget& Widget::operator=(Widget&&) noexcept = default;
int Widget::size() const { return int(impl_->items.size()); }

Now changing the private members, or the libraries they use, recompiles only widget.cpp. The costs are a heap allocation per object and an extra indirection on every access, so use it for big, stable-interface classes (subsystems, library facades), not for small value types in hot loops. Pimpl also gives a stable ABI for shared libraries, which is why Qt uses it everywhere.

include-what-you-use

include-what-you-use (IWYU) is a Clang-based tool that reads each file and reports which #includes it should add (things it uses but gets only indirectly) and remove (things it doesn't use), and where a forward declaration would do. It isn't installed in this course's image, so here is what a run looks like on the "heavy" version above (sample output):

bash
$ cmake -S . -B build -G Ninja -DCMAKE_CXX_INCLUDE_WHAT_YOU_USE=include-what-you-use
$ cmake --build build
src/scene.hpp should add these lines:
class Texture;

src/scene.hpp should remove these lines:
- #include "texture.hpp"  // lines 2-2

The full include-list for src/scene.hpp:
class Texture;
---
  • CMake runs it alongside every compile through CMAKE_<LANG>_INCLUDE_WHAT_YOU_USE (or the <LANG>_INCLUDE_WHAT_YOU_USE target property); fix_includes.py applies the suggestions.
  • Its suggestions need review: it doesn't know your project's "umbrella" headers unless you give it mapping files (.imp), and it may suggest private implementation headers of libraries.
  • clangd (the language server in VS Code, CLion and others) has a lighter include cleaner that flags unused includes in the editor, and clang-tidy's misc-include-cleaner check does the same in CI.

Habits that keep headers lean

  • Include in the .cpp, forward-declare in the .hpp.
  • Put heavy implementation details (templates you don't need inline, third-party types) behind functions or Pimpl.
  • Keep "everything" headers (common.hpp, stdafx.h) out of public headers; if you want them, use them as a PCH.
  • Check the effect with the deterministic measures from Header Cost: preprocessed lines and include fan-out.

Test yourself

A header only uses Texture* and const Texture&. What does it need?

  1. #include "texture.hpp"
  2. A forward declaration class Texture;
  3. A PCH
  4. Nothing at all

After switching scene.hpp to a forward declaration, editing texture.hpp recompiled one file instead of six. Why?

  1. Ninja got faster
  2. Only scene.cpp still includes texture.hpp, so only it depends on it
  3. ccache cached the others
  4. The unity build merged them

What does Pimpl trade for faster incremental builds?

  1. Nothing
  2. A heap allocation and an extra indirection per object
  3. Thread safety
  4. Exceptions