SyntaxPilot
Courses/C++/Lesson 35
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ · Lesson 35 of 40

Build basics: compiling, linking, CMake

queued

These are the notes for C++ episode 35. Every program so far lived in one main.cpp. Real projects have hundreds of files. This episode splits a program into files, meets the two very different errors that follow ("was not declared in this scope" from the compiler and "undefined reference" from the linker), and builds the tools that put it back together: declarations, header files with #pragma once, object files, the linker, and CMake. Every command below was run for real with g++ 13.3, GNU ld and CMake 3.28 on Ubuntu 24.04; the outputs are copied from those runs (the random /tmp/cc....o names change every run).

The problem: one huge file

Ravi's chai stall billing app has grown: menu, bills, GST, stock and reports, all in one main.cpp, 2,000 lines long.

  • Three friends edit the same file, so their changes clash.
  • Fixing one typo means the compiler reads all 2,000 lines again. In a real project that is minutes of waiting, many times a day.

The fix in real life: a cookbook is split into chapters. So we split the program by topic: main.cpp, bill.cpp, menu.cpp. Each person can own a file, and (the goal) only the file that changed gets recompiled.

Step 1: split it, and the first error

bill.cpp:

int billTotal(int cups, int price) {
    return cups * price;
}

main.cpp:

#include <iostream>
using namespace std;

int main() {
    int total = billTotal(3, 20);      // 3 chai at 20 rupees
    cout << "Bill: " << total << " rupees" << endl;
    return 0;
}
$ g++ main.cpp -o chai
main.cpp: In function ‘int main()’:
main.cpp:5:17: error: ‘billTotal’ was not declared in this scope
    5 |     int total = billTotal(3, 20);      // 3 chai at 20 rupees
      |                 ^~~~~~~~~

Why: the compiler works on one .cpp file at a time. One .cpp file plus everything it #includes is a translation unit, and each one is compiled on its own. bill.cpp was never opened. Inside a file the compiler also reads top to bottom: it only knows names it has already seen above the current line.

The same error in one file, when the function is written below main:

#include <iostream>
using namespace std;

int main() {
    int total = billTotal(3, 20);
    cout << "Bill: " << total << " rupees" << endl;
    return 0;
}

int billTotal(int cups, int price) {
    return cups * price;
}
main.cpp: In function 'int main()':
main.cpp:5:17: error: 'billTotal' was not declared in this scope
    5 |     int total = billTotal(3, 20);
      |                 ^~~~~~~~~

Step 2: declaration vs definition

A declaration is a promise: the function's name, parameters and return type, ending in ;, with no body. A definition is the real code, the body.

int billTotal(int cups, int price);              // declaration: a promise
int billTotal(int cups, int price) {             // definition: the body
    return cups * price;
}

Declaration only, no body anywhere:

#include <iostream>
using namespace std;

int billTotal(int cups, int price);    // declaration: a promise

int main() {
    int total = billTotal(3, 20);
    cout << "Bill: " << total << " rupees" << endl;
    return 0;
}
/usr/bin/ld: /tmp/ccOH2k9V.o: in function `main':
main.cpp:(.text.startup+0x15): undefined reference to `billTotal(int, int)'
collect2: error: ld returned 1 exit status

A different error. It has no line number, and it comes from ld, the linker, not from the compiler. The compiler trusted the promise; the linker then looked for the body and found nothing. Add the definition below main and it prints Bill: 60 rupees.

Rule: you may declare a function many times; you must define it exactly once in the whole program.

Step 3: two stages, the compiler and the linker

Building a C++ program is two jobs (think of a team writing a book):

 main.cpp ──compile──▶ main.o ─┐
 bill.cpp ──compile──▶ bill.o ─┼──link──▶ chai   (the program)
 menu.cpp ──compile──▶ menu.o ─┘
Stage Tool Input → output Its errors look like
Preprocess the preprocessor (cpp, run by g++) .cpp + headers → one big text fatal error: bill.h: No such file or directory
Compile the compiler (cc1plus, run by g++) one translation unit → an object file .o main.cpp:5:17: error: ... (file:line:column)
Link the linker (ld, run by g++) all .o files + libraries → the program undefined reference to ..., multiple definition of ..., ld returned 1 exit status

Tip: an error with a line number came from the compiler; an error with no line number and ld in it came from the linker.

Back to two files, with the declaration at the top of main.cpp:

$ g++ main.cpp -o chai
/usr/bin/ld: /tmp/ccX9LN0F.o: in function `main':
main.cpp:(.text+0x17): undefined reference to `billTotal(int, int)'
collect2: error: ld returned 1 exit status
$ g++ main.cpp bill.cpp -o chai
$ ./chai
Bill: 60 rupees

g++ main.cpp bill.cpp compiles each file and then links both object files together.

Step 4: header files and #include

Copying the declaration into every file that needs it breaks as soon as someone changes the function. The fix is a header file: the declarations written once, like one printed menu card copied to every table.

bill.h:

#pragma once
struct Item {
    const char* name;
    int price;
};
int billTotal(int cups, int price);
int addGst(int amount);

bill.cpp:

#include "bill.h"

int billTotal(int cups, int price) {
    return cups * price;
}
int addGst(int amount) {
    return amount + amount * 5 / 100;   // 5% GST
}

menu.h and menu.cpp:

#pragma once
#include "bill.h"
void printMenu();
#include <iostream>
#include "menu.h"
using namespace std;

void printMenu() {
    Item chai = {"Masala chai", 20};
    cout << chai.name << ": " << chai.price << endl;
}

main.cpp:

#include <iostream>
#include "bill.h"
#include "menu.h"
using namespace std;

int main() {
    printMenu();
    int total = addGst(billTotal(10, 20));
    cout << "Bill with GST: " << total << " rupees" << endl;
    return 0;
}
$ g++ main.cpp bill.cpp menu.cpp -o chai && ./chai
Masala chai: 20
Bill with GST: 210 rupees
  • #include <iostream>: angle brackets for system and library headers.
  • #include "bill.h": double quotes for your own headers; the compiler looks in the current file's folder first.
  • bill.cpp includes its own header: if the declaration and the definition ever disagree, you find out at once.
  • #include is plain copy and paste, done by the preprocessor before compiling. You can see its output with g++ -E:
$ g++ -E main.cpp | grep -v '^#' | grep -v '^$' | tail -12
};
int billTotal(int cups, int price);
int addGst(int amount);
void printMenu();
using namespace std;
int main() {
    printMenu();
    int total = addGst(billTotal(10, 20));
    cout << "Bill with GST: " << total << " rupees" << endl;
    return 0;
}

Step 5: included twice, #pragma once

Remove #pragma once from bill.h and build again:

$ g++ main.cpp bill.cpp menu.cpp -o chai
In file included from menu.h:2,
                 from main.cpp:3:
bill.h:1:8: error: redefinition of ‘struct Item’
    1 | struct Item {
      |        ^~~~
In file included from main.cpp:2:
bill.h:1:8: note: previous definition of ‘struct Item’
    1 | struct Item {
      |        ^~~~

main.cpp includes bill.h, then menu.h, which includes bill.h again, so the struct is pasted into main.cpp twice. #pragma once tells the preprocessor to paste a file at most once per translation unit. The older, fully standard way is an include guard:

#ifndef BILL_H
#define BILL_H
// ... the header ...
#endif

Both work with every major compiler. Put one at the top of every header.

Step 6: a body in a header, the one definition rule

#pragma once
struct Item {
    const char* name;
    int price;
};
int billTotal(int cups, int price);
int addGst(int amount);
int discount(int amount) {             // a body inside the header
    return amount - 10;
}
$ g++ main.cpp bill.cpp menu.cpp -o chai
/usr/bin/ld: /tmp/ccHbXYm5.o: in function `discount(int)':
bill.cpp:(.text+0x0): multiple definition of `discount(int)'; /tmp/ccNqrnbX.o:main.cpp:(.text+0x0): first defined here
/usr/bin/ld: /tmp/ccTEgTK1.o: in function `discount(int)':
menu.cpp:(.text+0x0): multiple definition of `discount(int)'; /tmp/ccNqrnbX.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

#pragma once only stops a double paste inside one .cpp. Three .cpp files include bill.h, so three object files each contain a body of discount, and the linker finds three. This breaks the one definition rule (ODR): a function (or global variable) has exactly one definition in the whole program.

Fixes (both tested: Bill with GST: 210 rupees):

  1. Keep only the declaration int discount(int amount); in the header and the body in bill.cpp.
  2. For a tiny function, write inline int discount(int amount) { ... }: inline allows identical copies in several files, and the linker keeps one. (Class member functions written inside the class body and templates are inline automatically, which is why they live in headers.)

Headers hold declarations; .cpp files hold bodies.

Step 7: object files and symbols

-c means compile only, don't link. Each .cpp becomes an object file (.o): machine code with "holes" for functions defined elsewhere.

$ g++ -c main.cpp && g++ -c bill.cpp && g++ -c menu.cpp && ls *.o
bill.o
main.o
menu.o

nm lists an object file's symbols (the names inside it); -C shows C++ names readably.

$ nm -C bill.o
0000000000000017 T addGst(int)
0000000000000000 T billTotal(int, int)
$ nm -C main.o          (library lines left out)
                 U addGst(int)
                 U billTotal(int, int)
                 U printMenu()
0000000000000000 T main
  • T: this file has the body (text = code).
  • U: undefined here, "someone else has the body".

The linker's job is to match every U with exactly one T. No T: undefined reference. Two T's: multiple definition.

$ g++ main.o bill.o menu.o -o chai && ./chai
Masala chai: 20
Bill with GST: 210 rupees

If only bill.cpp changes, recompile only bill.o and link again. In a project with 1,000 files that is the difference between seconds and many minutes.

Step 8: CMake

Typing one g++ -c per file, remembering which files changed (and which headers they include), and using different commands on Windows doesn't scale. CMake is a build system generator: you describe your program once in CMakeLists.txt, and CMake writes the real build commands (Makefiles, Ninja files or Visual Studio projects) for your compiler and system.

cmake_minimum_required(VERSION 3.16)
project(ChaiStall CXX)
set(CMAKE_CXX_STANDARD 17)

add_executable(chai main.cpp bill.cpp menu.cpp)
Line Meaning
cmake_minimum_required(VERSION 3.16) the oldest CMake that may build this
project(ChaiStall CXX) the project's name, written in C++
set(CMAKE_CXX_STANDARD 17) compile with C++17
add_executable(chai main.cpp bill.cpp menu.cpp) a program called chai built from these files (headers are found through the #includes)

Configure once (-S . = the source is this folder, -B build = put everything generated in build/):

$ cmake -S . -B build
-- The CXX compiler identification is GNU 13.3.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.1s)
-- Generating done (0.0s)
-- Build files have been written to: /home/student/chai/v3/build

Build:

$ cmake --build build
[ 25%] Building CXX object CMakeFiles/chai.dir/main.cpp.o
[ 50%] Building CXX object CMakeFiles/chai.dir/bill.cpp.o
[ 75%] Building CXX object CMakeFiles/chai.dir/menu.cpp.o
[100%] Linking CXX executable chai
[100%] Built target chai
$ ./build/chai
Masala chai: 20
Bill with GST: 210 rupees

Incremental build: nothing changed, nothing is compiled. Change GST in bill.cpp from 5% to 18%, and only bill.cpp is recompiled:

$ cmake --build build
[100%] Built target chai
$ cmake --build build && ./build/chai          (after editing bill.cpp)
[ 25%] Building CXX object CMakeFiles/chai.dir/bill.cpp.o
[ 50%] Linking CXX executable chai
[100%] Built target chai
Masala chai: 20
Bill with GST: 236 rupees

If you edit bill.h, CMake recompiles every .cpp that includes it, because it tracks header dependencies for you.

Cheat sheet

Need Command or code
Build several files at once g++ main.cpp bill.cpp -o chai
Compile only (make .o) g++ -c bill.cpp
Link object files g++ main.o bill.o -o chai
See the preprocessor's output g++ -E main.cpp
List symbols nm -C bill.o (T = has the body, U = needs it)
Header guard #pragma once (or #ifndef X / #define X / #endif)
A tiny function in a header inline int f(int x) { ... }
CMake: configure cmake -S . -B build
CMake: build cmake --build build
CMake: a program add_executable(name a.cpp b.cpp)
CMake: a library add_library(name x.cpp) + target_link_libraries(prog PRIVATE name)
Useful flags -Wall -Wextra (warnings), -O2 (optimise), -g (debug info), -std=c++17

Common mistakes

Mistake Real error Fix
Calling a function with no declaration above error: 'billTotal' was not declared in this scope #include "bill.h" (or declare it)
Forgetting a .cpp when building undefined reference tobillTotal(int, int)'/ld returned 1 exit status|g++ main.cpp bill.cpp, or add it toadd_executable`
Header without #pragma once, included twice error: redefinition of 'struct Item' #pragma once
A function body in a header included by several .cpp files multiple definition ofdiscount(int)'| body in the.cpp, orinline`
A declared member function that is never defined undefined reference toAccount::deposit(int)'| write the body in the.cpp`
Wrong header name in #include fatal error: bil.h: No such file or directory fix the name or the include path

Mini project: the bank account as a library

Split the bank account class (classes episodes) into account.h / account.cpp, make it a library with CMake, and link the program to it.

account.h:

#pragma once
#include <string>

class Account {
public:
    Account(std::string owner, int balance);
    void deposit(int amount);
    bool withdraw(int amount);
    int balance() const;
    std::string owner() const;
private:
    std::string owner_;
    int balance_;
};

account.cpp:

#include "account.h"

Account::Account(std::string owner, int balance) : owner_(owner), balance_(balance) {}

void Account::deposit(int amount) { balance_ += amount; }

bool Account::withdraw(int amount) {
    if (amount > balance_) return false;
    balance_ -= amount;
    return true;
}

int Account::balance() const { return balance_; }
std::string Account::owner() const { return owner_; }

main.cpp:

#include <iostream>
#include "account.h"
using namespace std;

int main() {
    Account a("Priya", 500);
    a.deposit(250);
    cout << a.owner() << ": " << a.balance() << endl;
    cout << (a.withdraw(1000) ? "withdrawn" : "not enough money") << endl;
    return 0;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.16)
project(Bank CXX)
set(CMAKE_CXX_STANDARD 17)

add_library(account account.cpp)          # a library: reusable code, no main
add_executable(bank main.cpp)
target_link_libraries(bank PRIVATE account)
$ cmake -S . -B build > /dev/null && cmake --build build && ./build/bank
[ 25%] Building CXX object CMakeFiles/account.dir/account.cpp.o
[ 50%] Linking CXX static library libaccount.a
[ 50%] Built target account
[ 75%] Building CXX object CMakeFiles/bank.dir/main.cpp.o
[100%] Linking CXX executable bank
[100%] Built target bank
Priya: 750
not enough money

Account::deposit written in the class as ClassName::function is how a member function is defined outside the class. A static library (libaccount.a) is a bundle of object files that the linker copies what it needs from.

Practice

  1. Split your own bank account (or student) class into a header and a .cpp, and build it with plain g++.
  2. Cause all four errors on purpose and read each one: not declared, undefined reference, redefinition, multiple definition.
  3. Run nm -C on your object files and find the T and U lines.
  4. Build it with CMake, change one .cpp, rebuild, and check that only that file is recompiled.
Solutions

1 and 4: the mini project above is a full solution. With plain g++: g++ main.cpp account.cpp -o bank.

2: the four programs and their exact errors are in steps 1, 2, 5 and 6 above. A missing member body gives the same linker error with the class name; deleting the deposit line from account.cpp:

$ g++ main.cpp account.cpp -o bank
/usr/bin/ld: /tmp/ccnkUprU.o: in function `main':
main.cpp:(.text+0x7e): undefined reference to `Account::deposit(int)'
collect2: error: ld returned 1 exit status

3: nm -C on the library from the mini project lists every member function the library defines as T:

$ nm -C build/libaccount.a | grep " T "
0000000000000038 T Account::deposit(int)
000000000000005e T Account::withdraw(int)
0000000000000000 T Account::Account(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)
0000000000000000 T Account::Account(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)
00000000000000b0 T Account::owner[abi:cxx11]() const
000000000000009a T Account::balance() const

(The constructor appears twice because g++ emits two versions of it, a "complete" and a "base" constructor; that is normal.)

Quick quiz

// bill.h  (no #pragma once)
int addGst(int amount);

// main.cpp
#include "bill.h"
int main() { return addGst(100); }

// g++ main.cpp -o chai

Which error do you get?

Answer

**undefined reference toaddGst(int)'**. The header gives the compiler the declaration, somain.cppcompiles. But no.cppwith the body was given to g++, so the linker can't find it. The missing#pragma once` doesn't matter here: the header is included only once.

Interview questions

  1. Declaration vs definition? A declaration introduces a name and its type (a promise); a definition provides the body or storage. Many declarations, one definition.
  2. What does "undefined reference" mean? The linker found a call (a U symbol) but no object file or library defines it: a missing .cpp, a missing library, or a body never written.
  3. What are the stages of building a C++ program? Preprocess (#include, macros), compile each translation unit to an object file, link the object files and libraries into an executable.
  4. What is a translation unit? One .cpp file after the preprocessor has pasted in all its includes.
  5. Why do we need include guards? To stop a header being pasted twice into one translation unit, which causes redefinition errors.
  6. What is the one definition rule? Each function and global variable has exactly one definition in the program (with exceptions for inline functions and templates, whose identical definitions may appear in several translation units).
  7. Why put templates in headers? The compiler needs the template's body in every translation unit that uses it to generate code; templates are inline by nature.
  8. What does CMake do? It generates the build system (Makefiles, Ninja, Visual Studio projects) from CMakeLists.txt, tracks dependencies, and rebuilds only what changed.
  9. Static vs shared library? A static library (.a, .lib) is copied into the program at link time; a shared library (.so, .dll) is loaded when the program runs, and several programs can share it.

Glossary

Term Meaning, with an example
source file A .cpp file with your code, like bill.cpp.
header file A .h file with declarations to share, like bill.h.
#include Pastes a file's text in: #include "bill.h".
preprocessor The first step of a build: handles #include, #pragma, #define. See it with g++ -E.
translation unit One .cpp plus everything it includes, compiled on its own.
declaration A promise that a name exists: int billTotal(int cups, int price);
definition The real body: int billTotal(int c, int p) { return c * p; }
scope The part of the code where a name is known.
compiler Turns one translation unit into an object file; its errors have line numbers.
object file The compiled .o file for one .cpp: machine code with holes.
g++ -c Compile only, don't link.
linker (ld) Joins object files and libraries into one program, connecting each call to its body.
symbol A named function or variable inside an object file.
nm Lists symbols: T = defined here, U = needed from elsewhere.
undefined reference Linker error: a symbol is used but never defined.
collect2: error: ld returned 1 exit status g++'s note that the linker failed.
redefinition Compiler error: the same thing defined twice in one translation unit.
multiple definition Linker error: the same function defined in two object files.
one definition rule (ODR) One definition per function or global variable in the whole program.
#pragma once Paste this header at most once per translation unit.
include guard The #ifndef / #define / #endif way to do the same.
inline Allows identical definitions in several files; the linker keeps one.
executable The finished program you run: ./chai.
library Reusable compiled code without main, like libaccount.a.
build system A tool that runs the right compile and link commands for you.
CMake A build system generator driven by CMakeLists.txt.
CMakeLists.txt The file that tells CMake what to build from which files.
configure cmake -S . -B build: CMake finds the compiler and writes build files.
add_executable CMake: build a program from source files.
add_library CMake: build a library.
target_link_libraries CMake: link a program to a library.
incremental build Rebuilding only what changed since the last build.

Summary

  • Big programs are split into many .cpp files; each is compiled on its own (a translation unit).
  • A declaration is a promise; a definition is the body, exactly once.
  • Compiler errors have line numbers; linker errors (undefined reference, multiple definition) don't.
  • Headers hold declarations and start with #pragma once; .cpp files hold bodies.
  • g++ -c makes object files; the linker matches every U with one T.
  • CMake: write CMakeLists.txt, cmake -S . -B build once, then cmake --build build, which rebuilds only what changed.

Next episode: Ravi has 200,000 bills and 200,000 questions. DSA 1: sorting and binary search with the STL.