Circular Include in C++
A simple mistake as C++ project grows.
1. Introduction
When a C++ project grows, #include mistakes start showing up as:
- error: incomplete type
- “unknown type name”
- “invalid use of incomplete type”
and so on …
An include cycle happens when headers form a loop:
Once your include graph contains a loop, it becomes very easy to hit problems where a type is referenced before it’s fully defined.
A minimal circular include example:
1 | // A.h |
2. Solution: Forward Declaration
1 | // A.h |
Forward declarations only work when we store the objects as pointers or references. The following example will fail if we try to store an actual object.
1 | // A.h |
The most effective pattern to avoid include cycles is to:
- Forward declaration in headers.
- Includes in cpp files.
1 | // A.h |
3. Inline Functions
Even if you forward declare, inline methods in headers can force full includes. The error messages indicate that we are trying to access the mmeber function of class A, however type completeness is still missing even with forward declaration.
1 | // A.h |
Circular Include in C++
