The planner now has a record, a parser, validation and a summary. Keeping them in one file with main causes two problems: the test program needs the same functions but its own main, and a program cannot have two; and every reader must scroll past the implementation to learn what the functions promise. C++ solves both by splitting code into a header that declares what exists and a source file that defines how it works.
A header, such as planner.h, shares declarations and record definitions. A source file, such as planner.cpp, supplies the function bodies. main.cpp and test_planner.cpp each include the header, and each executable is built from one of them plus planner.cpp.
Predict and run
#include <iostream>
int twice(int value);
int twice(int value) {
return value * 2;
}
int main() {
std::cout << twice(6) << "\n";
return 0;
}Check your prediction
12The first twice line is a declaration: it ends in a semicolon and tells the compiler the function's name, parameters and return type. The second is a definition: it has a body. A call only needs the declaration to be visible above it. That is the whole idea behind headers: the declaration goes in the header, which every user includes, and the definition goes in exactly one source file.
How the pieces fit together
Building a multi-file program happens in two stages. First, the compiler processes each .cpp file on its own, with every #include pasted in, and checks that each call matches a visible declaration. Second, the linker connects every call to the one definition that provides it, and joins the results into an executable.
The planner's header looks like this, shortened:
#ifndef STUDY_PLANNER_H
#define STUDY_PLANNER_H
#include <string>
#include <vector>
struct Task {
std::string title;
int minutes = 0;
bool done = false;
};
struct Summary {
int planned = 0;
int completed = 0;
int remaining = 0;
};
// Durations are 1..180. Failure leaves out unchanged.
bool parse_task(const std::string& line, Task& out);
Summary summarize(const std::vector<Task>& tasks);
#endif- Your own header is included with quotes,
#include "planner.h"; standard headers use angle brackets,#include <vector>. - The
#ifndef/#define/#endiflines are a header guard. If a file includes the header twice, directly or through another header, the second copy is skipped instead of definingTasktwice. - Never
#includea.cppfile. Doing so pastes its definitions into a second place, and the linker then finds two definitions of the same function.
Compile errors and link errors
Because the stages are separate, there are two different kinds of failure. If a declaration is missing, the compiler stops: use of undeclared identifier. If a declaration is present but no definition is ever built into the program, every file compiles and the linker fails. Renaming a function in planner.cpp but not in planner.h causes this. In this browser and on macOS the linker says undefined symbol; on Linux it says undefined reference. Either way, it names the function:
undefined symbol: parse_task(std::string const&, Task&)Check spelling and parameter types on both sides, and check that the defining source file is part of the build command.
What you will use
- A header with a guard.
#ifndef/#define/#endifaround the declarations, each with a one-line contract comment. #include "durations.h"in every file that calls or defines the functions, with quotes because the header is yours.- Definitions in their own source file. Bodies that match their declarations exactly, in
durations.cpp. - A
const std::vector<int>¶meter. The function reads the values without copying them. - Assertions in
main.cpp. The test entry point, kept separate from the functions it tests.
Plan before you type
- In
durations.h, write the guard and the two declarations, each with its contract comment. - In
main.cpp, include the header and write the assertions, before any function bodies exist. - Run once and read the error: every file compiles, and the build fails at the link stage, because nothing defines the functions yet.
- In
durations.cpp, write the two definitions so they match the declarations exactly. - Run until
Accepted total checks passedprints.
Prove it can fail
With the checks passing, rename the definition of valid_minutes in durations.cpp to valid_minute but leave its declaration alone. The build should fail with a link error naming valid_minutes(int), even though every file compiles: the call found a declaration but no definition. Restore the name. Then include the header a second time in main.cpp and delete the guard lines: it still builds, because a function may be declared more than once. Put the guard back anyway. The planner's header also defines struct Task, and a second copy of a definition is an error. Finally delete the #include "durations.h" line from main.cpp: now the compiler stops at the first call, because nothing in that file declares the function.
Mistakes worth checking for
undefined referenceorUndefined symbolsat the end of the build: a declared function has no matching definition, often because a parameter type differs, such asstd::vector<int>in one place andconst std::vector<int>&in the other.use of undeclared identifier: the file that calls the function does not include the header.'durations.h' file not found: the name in quotes does not match the tab's name exactly.redefinition of 'Task': a header without a guard was included twice.duplicate symbolormultiple definition of 'main': two files with amainwere built into the same executable, such asmain.cppandtest_planner.cpptogether.
Practice
Your turn
Build a three-file program in the tabs below, laid out the way the planner is:
durations.h: a header guard, thenbool valid_minutes(int minutes);andint accepted_total(const std::vector<int>& values);, each with a one-line contract comment. Valid durations are 1 to 180 minutes, andaccepted_totalsums only valid values.durations.cpp: includes the header and defines both functions.main.cpp: includes the header and asserts that 25, 0, 181 and 10 give 35, that an empty vector gives 0, and that the edges 1 and 180 give 181. When all pass, it prints:
Accepted total checks passedThe browser compiles every .cpp tab and links them into one program, just like c++ main.cpp durations.cpp on your own computer. Your edits are saved in this browser.
Hint 1: the idea
The header holds only promises: names, parameter types and return types. Both .cpp files include it, so main.cpp can call the functions and durations.cpp is checked against the same promises. The linker then joins the call in one file to the body in the other.
Hint 2: a first step
Fill in durations.h and the assertions in main.cpp first, and leave durations.cpp as it is. Run: you should get a link error naming accepted_total (the wording varies: undefined symbol or undefined reference), not a compile error. That proves the header is right and only the definitions are missing.
Show one solution
main.cpp compiles because the header it includes promises that the functions exist, and the program links because durations.cpp keeps that promise with identical signatures. durations.cpp includes the same header, so if a definition drifts from its declaration (a missing const or &), the mismatch shows up in this project instead of in a caller's build. The solution's main.cpp includes the header twice on purpose: the guard makes the second copy empty. The edge case 1 plus 180 catches an off-by-one in either bound. The planner uses exactly this layout, as the tabs below show.
Run the project helper tests
The project tabs separate planner.h, planner.cpp and test_planner.cpp. Read the header's comments as contracts, then run the tests. They have their own main, intentionally separate from the application's entry point in main.cpp.
Check your prediction
Planner checks passedcomplete_task takes a std::size_t index and checks it against size() before touching an element; the tests pass tasks.size(), the first invalid index, to prove the check. A negative number converted to std::size_t becomes a huge value, which only that check rejects. In a tab, rename one declaration without changing its definition, read the diagnostic, then press Reset.
Completion is saved in this browser only. It does not measure mastery.