1. Goals
Separate a shared interface from function implementations.
Compile several source files into one program.
Distinguish compilation errors from missing or duplicate definitions at link time.
2. Prerequisites
You know functions, classes/structs, const references, std::string,
std::vector, and templates. This lesson uses ordinary functions to focus
on file organization; CMake and C++20 modules are unnecessary here.
3. Explanation
A program need not keep everything in main.cpp. Here, main.cpp creates
a book list and prints results; book.cpp implements two queries;
book.hpp is a header describing the data type and function interfaces.
The .hpp extension is a C++ header naming convention, not a special
linking mechanism.
A function declaration gives its name, return type, and parameter
types so callers can be checked. For example, bool hasTitle(const
std::vector<Book>& books, const std::string& title); ends with ; and
has no body. A function definition includes the { ... } body that
does the work. Signatures in the header and book.cpp must match,
including const and &.
#include "book.hpp" brings the header contents into the file being
processed. A .cpp file together with its included headers forms a
translation unit. The compiler checks each translation unit separately;
it does not automatically discover every .cpp in the directory.
The #ifndef/#define pair and #endif form an include guard. If
the header is included more than once in the same translation unit, the
guard prevents repeated definitions of Book there. The header includes
<cstddef>, <string>, and <vector> itself because its interface needs
std::size_t, std::string, and std::vector. Users should not need to
guess an include order. Do not put using namespace std; in a shared header.
Book is defined in the header so its users know its members. Identical
class definitions in different translation units, subject to the
one-definition rule's conditions, are a normal organization technique.
The two non-inline free functions here are different: each needs one
definition in the entire program. Include guards cannot fix two
definitions of these functions in different translation units.
Compiling with -c creates an object file, .o; it can contain calls
not yet connected to their implementations. Linking combines object
files, resolves those calls to definitions, and produces an executable.
Using g++ for linking C++ also supplies the required C++ libraries.
countLongBooks counts books with at least the requested number of
pages; an empty list returns 0. hasTitle compares exact,
case-sensitive titles and returns false when absent. Both functions
only read the list. The sample records have nonnegative page counts;
these queries do not validate or repair records.
The templates from the previous lesson generally need their definitions
in an included header where instantiation occurs. Do not apply the
ordinary-function split into book.cpp to every template. Also, do not
#include "book.cpp" in main.cpp; compile that source and link it once.
4. Runnable example
Create all three files in the same directory, with the names shown.
Copying only main.cpp is insufficient to build this program.
File book.hpp:
#ifndef FOUNDATION_BOOK_HPP
#define FOUNDATION_BOOK_HPP
#include <cstddef>
#include <string>
#include <vector>
struct Book {
std::string title;
int pages;
};
std::size_t countLongBooks(const std::vector<Book>& books, int minimumPages);
bool hasTitle(const std::vector<Book>& books, const std::string& title);
#endifFile book.cpp:
#include "book.hpp"
std::size_t countLongBooks(const std::vector<Book>& books, int minimumPages) {
std::size_t count = 0;
for (const Book& book : books) {
if (book.pages >= minimumPages) {
++count;
}
}
return count;
}
bool hasTitle(const std::vector<Book>& books, const std::string& title) {
for (const Book& book : books) {
if (book.title == title) {
return true;
}
}
return false;
}File main.cpp:
#include "book.hpp"
#include <iostream>
#include <vector>
int main() {
const std::vector<Book> books{
{"C++ Basics", 120},
{"Learning Classes", 260},
{"Small Programs", 180}
};
std::cout << std::boolalpha;
std::cout << "Books with at least 180 pages: "
<< countLongBooks(books, 180) << '\n';
std::cout << "Has C++ Basics: " << hasTitle(books, "C++ Basics") << '\n';
std::cout << "Has Missing Book: " << hasTitle(books, "Missing Book") << '\n';
return 0;
}Run these commands in the directory containing the three files. The first compiles both sources and links them in one command:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror main.cpp book.cpp -o books
./booksIn Windows PowerShell, use -o books.exe and run .\books.exe.
Output:
Books with at least 180 pages: 2
Has C++ Basics: true
Has Missing Book: falseTo see the separate steps, compile and link individually; the output stays the same:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror -c main.cpp -o main.o
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror -c book.cpp -o book.o
g++ main.o book.o -o books5. Common mistakes
Running
g++ main.o -o books: definitions frombook.oare missing, typically causingundefined referenceorunresolved externalerrors.Running
g++ main.o book.o book.o -o books: the implementation is included twice, causingmultiple definitionorduplicate symbolerrors.Expecting include guards to prevent duplicate definitions across a whole program.
Changing a declaration without updating the
.cpp, accidentally creating an overload and leaving the signature called bymainundefined.Making a header depend on users including some other header first.
Compiling only the currently open editor file despite having multiple sources.
Running an old executable after the latest build failed.
6. Practice
Compile
main.cppandbook.cppseparately, then link them. Omitbook.ofrom the final command, then try including it twice. Both attempts must fail during linking; an old binary cannot test the failed new build.Add a second
#include "book.hpp"tomain.cpp. Compilation still succeeds thanks to the include guard. Explain why this does not fix the duplicatebook.oproblem.Test an empty list: the count is
0and a title search isfalse. With the sample list, a threshold of260gives1and261gives0.Add
bool hasBooks(const std::vector<Book>& books);to the header and define it inbook.cpp. Call it frommain.cpp, rebuild the program, and test both an empty list and the sample list.
7. Self-check
Why can
main.cppcompile intomain.obut fail to link withoutbook.o? Answer: the header's declarations suffice to check the calls. The function bodies needed by the executable are inbook.oand must be supplied to the linker.Does an include guard prevent the failure from
g++ main.o book.o book.o -o books? Answer: no. It prevents repeated inclusion within each translation unit; this link command still supplies the ordinary function definitions twice.Can you always declare a template in a header and hide its body in a
.cpp? Answer: not with the general approach learned here. Instantiation normally needs the definition, so put template definitions in a header. Explicit instantiation is another technique to study later.
Sample code
Source file
cpp98_foundation/24_headers_linking/main.cpp
#include "book.hpp"
#include <iostream>
#include <vector>
int main() {
const std::vector<Book> books{
{"C++ Basics", 120},
{"Learning Classes", 260},
{"Small Programs", 180}
};
std::cout << std::boolalpha;
std::cout << "Books with at least 180 pages: "
<< countLongBooks(books, 180) << '\n';
std::cout << "Has C++ Basics: " << hasTitle(books, "C++ Basics") << '\n';
std::cout << "Has Missing Book: " << hasTitle(books, "Missing Book") << '\n';
return 0;
}