6.7 — Splitting code into files

📘 Chapter 6⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Why split?#

Big programs get long. We split them into many files, each with one job.

Header and source files#

  • A header file (.h) holds declarations: "these functions exist".
  • A source file (.cpp) holds definitions: the actual code.

math.h

C++
#pragma once int add(int a, int b);int multiply(int a, int b);

math.cpp

C++
#include "math.h" int add(int a, int b){    return a + b;} int multiply(int a, int b){    return a * b;}

main.cpp

C++
#include <iostream>#include "math.h" int main(){    std::cout << add(2, 3) << '\n';    std::cout << multiply(2, 3) << '\n';    return 0;}

The include rules#

  • #include <iostream> with < > = a library file that came with C++.
  • #include "math.h" with " " = your own file.
  • #pragma once at the top of a header stops it being included twice.

Compiling many files#

In an IDE, add all .cpp files to the project. In a terminal, list them all:

text
g++ -std=c++20 main.cpp math.cpp -o app
Watch out

Never #include a .cpp file. Only include headers.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.