In C++, what is the difference between a declaration and a definition, and which of them belongs in a header file?
answer
- names something versus creates it
- a body or storage makes it a definition
- #include pastes text into each file
- class definitions may repeat across files
- extern int n; versus int n;
basics
~20 sA declaration introduces a name and its type; a definition also creates the entity: a function's body, a variable's storage. Headers hold declarations, class definitions and inline or template code; ordinary function and variable definitions go in exactly one .cpp file.
solid answer
~50 sA **declaration** introduces a name and its type so that code can refer to it: `int area(int w, int h);`, `extern int frame_count;`, `class Lidar;`. A **definition** is a declaration that also creates the thing: the function's body, the variable's storage, the class's full member list. Every definition is also a declaration, but not every declaration is a definition. `#include` pastes a header's text into every source file that names it, so whatever a header holds is compiled once per translation unit. That is why headers carry declarations, class definitions, and inline functions and templates, which the one-definition rule lets several translation units define identically, while a non-inline function body or a global variable's definition goes in exactly one `.cpp` file. Put one of those in a header and every file that includes it defines it again.
code
cpp · 19 lines#include <cstdio>
// What a header would hold: declarations only.
extern int tick_count; // declares a variable, no storage
int add_ticks(int n); // declares a function, no body
struct Odometry; // declares a class, which stays incomplete
struct Velocity { double v; }; // a class definition is shared too
// What exactly one .cpp file would hold: the definitions.
int tick_count = 0;
int add_ticks(int n) {
tick_count += n;
return tick_count;
}
int main() {
add_ticks(3);
std::printf("%d\n", add_ticks(4));
}go deeper
Recall the one-line rule: a declaration names something, a definition creates it. Give one example of each for a function, a variable and a class, and say which file each one lives in.
Explain #include as text pasted into every translation unit, then show why that makes a non-inline function body in a header fail at link time while a class definition there is fine.
Show that you keep headers lean on purpose: declarations and class definitions only, bodies and private helpers in the .cpp, so editing an implementation recompiles one file instead of every includer.
Treat each header as a published contract: what it exposes sets the rebuild cost and the coupling for every consumer, and that is the lever when a large codebase's build time keeps growing.
## Declarations and definitions in the standard's terms A **declaration** introduces a name into a translation unit and says what kind of thing it is: a function with these parameter and return types, a variable of this type, a class. That is enough for the compiler to check every use of the name. A **definition** is a declaration that also *creates* the entity. The C++ standard states it the other way round: every declaration is a definition **unless** it falls into one of a list of exceptions. The exceptions that matter day to day are: - a function declared **without a body**: `int area(int w, int h);` - a declaration with the `extern` specifier and **no initializer**: `extern int frame_count;` - a **non-inline static data member** declared inside its class: `static int limit;` - an **elaborated type specifier**, the forward declaration `class Lidar;` - a `typedef`, an alias declaration, a `using`-declaration or a `using`-directive So `int frame_count;` at namespace scope is a definition: it creates storage, and because it has static storage duration it is zero-initialized. `extern int frame_count = 0;` is a definition too, because the initializer outweighs the `extern`. ```cpp extern int frame_count; // declaration only int area(int w, int h); // declaration only class Lidar; // declaration only: Lidar is incomplete int frame_count = 0; // definition: storage int area(int w, int h) { // definition: body return w * h; } struct Pose { double x, y; }; // definition of the class Pose ``` ## What #include actually does `#include "pose.h"` is replaced by **the entire text** of `pose.h` before the compiler proper sees the file. The standard calls a source file, plus everything it includes, minus lines skipped by conditional compilation, a **translation unit**. Each `.cpp` file is compiled on its own into an object file, and the **linker** then joins the object files into one program, matching each use of a function or variable to its single definition. Two consequences follow: 1. A header is not compiled by itself. Its text is compiled again inside **every** translation unit that includes it, directly or through another header. 2. A call needs only a **declaration** in the calling file. The compiler emits a reference to the function's symbol, and the linker resolves it against whichever object file holds the definition. ## What goes where | Construct | Header | One `.cpp` file | |---|---|---| | Function declaration | yes | the definition | | Non-inline function body | no | yes | | `extern` variable declaration | yes | the definition | | Class definition | yes, it is shared | member function bodies | | Inline function, function template | yes, identical in every file | — | | File-private helpers | no | yes | The class definition is the interesting row. The one-definition rule says a **non-inline** function or variable is defined once in the whole program, but it allows a class, an inline function, an inline variable or a template to be defined in several translation units, **provided every definition is the same sequence of tokens with the same meaning**. A class must be defined in each translation unit that needs its size or members, so its definition has to live in a header. Within a single translation unit, though, each entity may still be defined at most once, which is the job of include guards. ## Why the split exists Separate compilation is what makes the split pay off. If `planner.cpp` changes, only `planner.cpp` is recompiled and the program relinked. If `planner.h` changes, every file that includes it is recompiled. Keeping bodies in `.cpp` files therefore keeps edits cheap, and keeping only declarations in headers keeps every includer independent of implementation details. ## Common mistakes - **A non-inline function body in a header.** It compiles, then the link fails as soon as two `.cpp` files include the header, because each object file now defines the function. - **A global variable defined in a header** as `int frame_count = 0;`: the same failure. The header should hold `extern int frame_count;` and one `.cpp` file the definition. - **Declaring without ever defining.** A function that is declared, called and defined nowhere compiles fine; the link then typically fails with an undefined symbol. - **Believing `#include` links code.** It copies text; linking is a later, separate step.
- Is int x; at namespace scope a declaration or a definition?A definition: it creates storage, and as a variable with static storage duration it is zero-initialized. Only `extern int x;` with no initializer is a pure declaration, and `extern int x = 0;` becomes a definition again because of the initializer. That is why a header that says `int x;` produces a duplicate definition as soon as two `.cpp` files include it.
- What does a .cpp file need before a call to a function in another file compiles?Only a declaration: the name, the parameter types and the return type, so the compiler can check the call and emit a reference to the function's symbol. The body can live in any other translation unit, and the linker connects the call to it. If no translation unit defines the function, every file still compiles and the link typically fails with an undefined-symbol error.
- Why can a class definition appear in many translation units when a function body cannot?The one-definition rule allows a class, an inline function, an inline variable and a template to be defined in several translation units as long as every definition is token-for-token identical with the same meaning. A non-inline function or variable gets no such allowance and must be defined once in the program. Inside one translation unit, any entity may be defined only once.
- A header file is compiled into its own object file.
- Declaration and definition are two words for the same thing.
- Function bodies belong in headers so the compiler can see them.
- #include links the other file's compiled code into this one.
- A forward declaration like class Lidar; defines an empty class.