Skip to content

Checkpoint: Organize Source Files

The Course
•
40 min study

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

Predict before running C++
#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
Text
12

The 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:

C++
#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 / #endif lines are a header guard. If a file includes the header twice, directly or through another header, the second copy is skipped instead of defining Task twice.
  • Never #include a .cpp file. Doing so pastes its definitions into a second place, and the linker then finds two definitions of the same function.

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:

Shell
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 / #endif around 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>& parameter. 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

  1. In durations.h, write the guard and the two declarations, each with its contract comment.
  2. In main.cpp, include the header and write the assertions, before any function bodies exist.
  3. Run once and read the error: every file compiles, and the build fails at the link stage, because nothing defines the functions yet.
  4. In durations.cpp, write the two definitions so they match the declarations exactly.
  5. Run until Accepted total checks passed prints.
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 reference or Undefined symbols at the end of the build: a declared function has no matching definition, often because a parameter type differs, such as std::vector<int> in one place and const 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 symbol or multiple definition of 'main': two files with a main were built into the same executable, such as main.cpp and test_planner.cpp together.

Practice

Exercise

Your turn

Build a three-file program in the tabs below, laid out the way the planner is:

  • durations.h: a header guard, then bool valid_minutes(int minutes); and int accepted_total(const std::vector<int>& values);, each with a one-line contract comment. Valid durations are 1 to 180 minutes, and accepted_total sums 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:
Text
Accepted total checks passed

The 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.

Your working space C++
#include <cassert> #include <iostream> #include <vector> // Include your header here. int main() { // Write the assertions here, then print the success message. return 0; } // Write the header guard, then declare valid_minutes and accepted_total, // each with a one-line contract comment. #include "durations.h" // Define valid_minutes and accepted_total here.
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
Run the solution C++
#include "durations.h" #include "durations.h" // A second include is harmless: the guard skips it. #include <cassert> #include <iostream> #include <vector> int main() { assert(accepted_total({25, 0, 181, 10}) == 35); assert(accepted_total({}) == 0); assert(accepted_total({1, 180}) == 181); std::cout << "Accepted total checks passed\n"; return 0; } #ifndef DURATIONS_H #define DURATIONS_H #include <vector> // Durations of 1..180 minutes are valid. bool valid_minutes(int minutes); // Sums only the valid durations. An empty vector gives 0. int accepted_total(const std::vector<int>& values); #endif #include "durations.h" bool valid_minutes(int minutes) { return minutes >= 1 && minutes <= 180; } int accepted_total(const std::vector<int>& values) { int total = 0; for (int value : values) { if (valid_minutes(value)) { total += value; } } return total; }

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.

Headers, definitions and checks C++
#include "planner.h" #include <cassert> #include <iostream> int main() { Task out{"Keep me", 77, true}; const std::vector<std::string> bad{ "", "0 0 Zero", "181 0 Long", "25 2 Flag", "25 0", "25 0 ", "no 0 Text", "25x 0 Text", "25 0Title", "25 1.5 Title", "25+0 Title", "25-0 Title", "99999999999999999999999999 0 Huge", "25 0 " + std::string(41, 'x'), "25 0 Title\nextra" }; for (const std::string& line : bad) { assert(!parse_task(line, out)); assert(out.title == "Keep me" && out.minutes == 77 && out.done); } assert(parse_task("1 0 Short", out) && out.minutes == 1 && !out.done); assert(parse_task("180 1 " + std::string(40, 'x'), out)); assert(out.minutes == 180 && out.done && out.title.size() == 40); std::vector<Task> tasks; Summary result = summarize(tasks); assert(result.planned == 0 && result.completed == 0 && result.remaining == 0); assert(!complete_task(tasks, 0)); Task original{"Read", 25, false}; assert(add_task(tasks, original)); original.title = "Changed"; assert(tasks[0].title == "Read"); assert(add_task(tasks, Task{"Review", 10, true})); assert(!add_task(tasks, Task{"Invalid", 0, false}) && tasks.size() == 2); assert(!add_task(tasks, Task{"", 25, false})); result = summarize(tasks); assert(result.planned == 35 && result.completed == 10 && result.remaining == 25); assert(!complete_task(tasks, tasks.size())); assert(!tasks[0].done); assert(complete_task(tasks, 0)); assert(complete_task(tasks, 0)); result = summarize(tasks); assert(result.planned == 35 && result.completed == 35 && result.remaining == 0); std::vector<Task> full; for (int i = 0; i < 100; ++i) { assert(add_task(full, Task{"Focus", 180, false})); } assert(!add_task(full, Task{"Extra", 1, false}) && full.size() == 100); assert(summarize(full).planned == 18000); std::cout << "Planner checks passed\n"; return 0; } #include "planner.h" #include <sstream> bool valid_task(const Task& task) { return task.minutes >= 1 && task.minutes <= 180 && !task.title.empty() && task.title.size() <= 40 && task.title.find_first_not_of(" \t") != std::string::npos && task.title.find_first_of("\r\n") == std::string::npos; } bool parse_task(const std::string& line, Task& out) { if (line.find_first_of("\r\n") != std::string::npos) { return false; } std::istringstream input(line); Task candidate; int done = 0; char separator = '\0'; if (!(input >> candidate.minutes) || !input.get(separator) || (separator != ' ' && separator != '\t')) { return false; } if (!(input >> done) || (done != 0 && done != 1)) { return false; } // Require whitespace between the done flag and the title. if (!input.get(separator) || (separator != ' ' && separator != '\t')) { return false; } std::getline(input >> std::ws, candidate.title); candidate.done = done == 1; if (!valid_task(candidate)) { return false; } out = candidate; return true; } bool add_task(std::vector<Task>& tasks, const Task& task) { if (tasks.size() >= 100 || !valid_task(task)) { return false; } tasks.push_back(task); return true; } Summary summarize(const std::vector<Task>& tasks) { Summary result; for (const Task& task : tasks) { result.planned += task.minutes; if (task.done) { result.completed += task.minutes; } else { result.remaining += task.minutes; } } return result; } bool complete_task(std::vector<Task>& tasks, std::size_t index) { if (index >= tasks.size()) { return false; } tasks[index].done = true; return true; } #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; }; // One line: minutes, 0/1 done flag, then a title of 1..40 characters. // Durations are 1..180. Failure leaves out unchanged. bool parse_task(const std::string& line, Task& out); // At most 100 tasks. Rejection leaves the vector unchanged. bool add_task(std::vector<Task>& tasks, const Task& task); // Caller supplies tasks accepted by add_task. Summary summarize(const std::vector<Task>& tasks); // Invalid indexes fail without changing any task. Repeating completion is safe. bool complete_task(std::vector<Task>& tasks, std::size_t index); #endif
Check your prediction
Text
Planner checks passed

complete_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.

Was this article helpful?

Your response is saved on this device.