C++ Source Files and Headers
What Is a .cpp File?
A .cpp file is an implementation file. It includes the headers it needs, defines functions and methods, and becomes one translation unit after preprocessing. The compiler processes each .cpp file independently.
Header and Source Pair
Header:
// include/math_demo/vector2.h
#pragma once
namespace math_demo {
class Vector2 {
public:
Vector2(double x, double y);
double length() const;
private:
double x_;
double y_;
};
} // namespace math_demo
Source file:
// src/vector2.cpp
#include "math_demo/vector2.h"
#include <cmath>
namespace math_demo {
Vector2::Vector2(double x, double y) : x_(x), y_(y) {}
double Vector2::length() const {
return std::sqrt(x_ * x_ + y_ * y_);
}
} // namespace math_demo
The header gives other files enough information to compile. The source file owns the actual function bodies.
Another Source File Uses the Header
// src/main.cpp
#include "math_demo/vector2.h"
#include <iostream>
int main() {
math_demo::Vector2 v(3.0, 4.0);
std::cout << v.length() << "\\n";
}
main.cpp does not need to see the body of Vector2::length(). It only needs the declaration from the header. The compiled body comes from vector2.cpp, and the linker connects the call later.
The Compile and Link Flow
main.cpp + included headers -> main.o
vector2.cpp + included headers -> vector2.o
main.o + vector2.o -> final executable
| Stage | What happens |
|---|---|
Compile main.cpp | The compiler checks that Vector2 and length() are declared. |
Compile vector2.cpp | The compiler emits machine code for Vector2::length(). |
| Link | The linker sees that main.o calls Vector2::length() and resolves that call to the definition in vector2.o. |
Common Mistakes
- Forgot to compile a
.cppfile: the code compiles, but linking fails with an undefined reference. - Function signature mismatch: the header declares one signature, but the
.cppdefines a different one. - Implementation in a header without
inline: multiple.cppfiles include the header, then the linker sees duplicate definitions. - Including
.cppfiles: usually a mistake. Include headers, compile source files separately.
What Comes Next
Once you know how headers and source files cooperate, the next step is understanding the compiler.