← All Posts

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.

Common Mistakes

  • Forgot to compile a .cpp file: the code compiles, but linking fails with an undefined reference.
  • Function signature mismatch: the header declares one signature, but the .cpp defines a different one.
  • Implementation in a header without inline: multiple .cpp files include the header, then the linker sees duplicate definitions.
  • Including .cpp files: 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.