Loading lessons...
Programs with Multiple Code Files
Programs with Multiple Code Files
Real programs don't live in one file: source files (.cpp) and header files (.h) are combined at compile time. C++ has specific rules for splitting code.
The pieces
- Source files (.cpp) hold function definitions - the actual bodies.
- Header files (.h) hold declarations - the prototypes that many files need to share.
#includecopies (pastes) the header's text into the source file at compile time.
// math.h
int add(int a, int b);
// math.cpp
#include "math.h"
int add(int a, int b) { return a + b; }
// main.cpp
#include "math.h"
int main() { return add(1, 2); }
Why headers exist
Suppose several .cpp files call add(). Every file needs the declaration, but the definition must appear exactly once - putting the body in every file would cause a duplicate-definition error. The solution: declare add in a shared header that every file includes, and define the body once in a single .cpp file. That's exactly why headers of prototypes solve the problem.
- Define a function once.
- Declare it as many times as you need.
Header guards: #ifndef
If a header is included twice, its text is repeated - and repeated declarations can break the build. The classic fix is a header guard:
#ifndef MATH_H
#define MATH_H
int add(int a, int b);
#endif
- The first time the header is included, MATH_H is undefined, so the contents are processed and MATH_H gets defined.
- On any later include, the condition is now false and the contents are skipped.
TL;DR
- .cpp files store definitions; .h files store declarations/prototypes.
#include "file.h"pastes the header text into the source file.- A function must be defined once but can be declared many times.
- Headers hold the shared prototypes so several files can call them.
- Header guards
#ifndef/#define/#endifprevent double-inclusion.