Module 0 · Getting started
0.1How a C++ program is built
What happens between the text you write and a program you can run: the preprocessor, the compiler and the linker, and how to tell a compile error from a link error.
On this page
- Key terms
- In 30 seconds
- Your first program
- main and the exit code
- The three steps of a build
- Step 1: the preprocessor
- #define
- Step 2: compiling
- Declarations and definitions
- Step 3: linking
- Building a program from two files
- Rules of thumb
- Under the hood
- Common pitfalls
- The declaration doesn’t match the definition
- Running an old executable after a failed build
- Try it yourself
Key terms
- source file
- A plain text file of C++ code that you write. Its name usually ends in
.cpp. - machine code
- Instructions the processor runs directly, stored as bytes. Processors can't run C++ text.
- compiler
- The program that turns C++ source into machine code. This course uses GCC (
g++) and Clang (clang++). - terminal
- A window where you type commands for the computer to run, such as a build command.
- build
- The whole process of turning source files into a program you can run. It has three steps: preprocess, compile, link.
- executable
- The file a build produces: a program the operating system can run.
main- The function every C++ program starts in. When
mainends, the program ends. - exit code
- The whole number
mainreturns to the operating system when the program ends.0means success; anything else means something went wrong. - preprocessor
- The first step of a build. It handles lines that start with
#, such as#include, by editing the text before the compiler reads it. - directive
- A line that starts with
#. It's an instruction for the preprocessor, not C++ code. #include- Tells the preprocessor to paste in the contents of another file, usually a header.
- header
- A file of declarations meant to be included by other files, such as
<print>from the standard library. #define- Tells the preprocessor to replace a name with some text everywhere after that line.
- standard library
- The functions and types that come with every C++ compiler. Their names start with
std::. - object file
- What the compiler makes from one source file: machine code, plus a list of the names it defines and the names it still needs. Its name ends in
.o. - symbol
- A name in an object file's table, such as a function, marked either as defined in that file or as needed from another.
- linker
- The last step of a build. It joins object files and libraries into one executable, and connects every use of a name to that name's definition.
- declaration
- Tells the compiler that a name exists and what its type is, such as
int square(int x);. - definition
- Gives a declared name its body. A function's definition is its code in braces.
- compile error
- The compiler can't make sense of a source file, so no object file is made. The message names a file and a line.
- link error
- Every file compiled, but the linker can't find the definition of a name (or finds two).
Your processor can’t run C++. It runs machine code: instructions stored as bytes. Before a C++ program can run, a set of tools turns your text into machine code, in three steps. Knowing those steps tells you what a build command does, and which step an error message came from, which is half of fixing it.
In 30 seconds
- You write C++ in source files (
.cpp). Every program starts in a function calledmain. - A build has three steps: the preprocessor pastes in included files, the compiler turns each source file into an object file, and the linker joins the object files into an executable.
g++ -std=c++23 hello.cpp -o helloruns all three steps;./helloruns the result.- A compile error means the compiler couldn’t understand a file. A link error means a function was declared but its definition was never found.
Your first program
Here’s a complete C++ program. Save it in a file called hello.cpp:
#include <print>
int main() {
std::println("Hello, world!");
return 0;
}Output
Hello, world!
Line by line:
#include <print>brings in the part of the standard library that prints text.int main()starts the function calledmain. Theintbefore it meansmaingives back a whole number when it ends. The()holds its inputs; here there are none. The braces{and}hold its body.std::println("Hello, world!");prints the text and moves to a new line.std::says thatprintlncomes from the standard library. The;ends the statement, like a full stop ends a sentence.return 0;endsmainand gives back0, which means “everything went fine”.
To build it, open a terminal (a window where you type commands) in the folder with hello.cpp, and run:
g++ -std=c++23 hello.cpp -o hello
./hello
The first line runs the build. g++ is the GCC compiler. -std=c++23 asks for C++23, the version of C++ this course uses. hello.cpp is your source file, and -o hello names the executable it makes. The second line runs that executable; ./ means “in this folder”. The next lesson, Setting up, shows how to install a compiler and adds the flags that catch mistakes.
main and the exit code
When main ends, the number it returns goes to the operating system as the program’s exit code. 0 means success. Any other number means something went wrong, and you choose what each number means. Scripts and build tools read it to decide whether to carry on.
#include <print>
int main() {
int errors = 2;
if (errors > 0) {
std::println("found {} errors", errors);
return 1;
}
std::println("all good");
return 0;
}std::println puts each value in place of a {} in the text. In a terminal, echo $? prints the exit code of the last command:
g++ -std=c++23 check.cpp -o check
./check
echo $?
That prints found 2 errors, then 1.
main is special: if it reaches its closing brace without a return, it returns 0 for you:
#include <print>
int main() {
std::println("Done");
}Output
Done
Key idea0 means success
An exit code of 0 says the program worked. Return something else when it didn’t, so whatever ran your program can tell.
The three steps of a build
g++ hello.cpp -o hello looks like one step, but it runs three tools one after another:
| Step | Takes | Makes | Errors from this step |
|---|---|---|---|
| 1. Preprocess | hello.cpp | The same text, with every #include pasted in | A missing header file |
| 2. Compile | The preprocessed text | An object file, hello.o | Compile errors: typos, unknown names, wrong types |
| 3. Link | Every object file, plus the standard library | The executable, hello | Link errors: a definition that’s missing or appears twice |
You can stop after each step to see what it made:
g++ -std=c++23 -E hello.cpp -o hello.ii # 1. preprocess only
g++ -std=c++23 -c hello.cpp -o hello.o # 1 and 2: compile, don't link
g++ hello.o -o hello # 3. link
-E stops after the preprocessor and -c stops after the compiler. Everything after # on these lines is a comment for you; the terminal ignores it.
Step 1: the preprocessor
The preprocessor works on text. It doesn’t know C++; it follows the lines that start with #, called directives, and hands the result to the compiler.
#include <print> is replaced by the whole contents of the <print> header, and every header that one includes. After this step, the six lines of hello.cpp become tens of thousands of lines; open hello.ii from the commands above to see them. Angle brackets (<print>) are for standard library headers. You’ll write your own headers in Module 8, and include them with quotes: #include "square.h".
Without the #include, the compiler has never heard of std::println, and says so:
int main() {
std::println("Hello, world!");
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:2:10: error: ‘println’ is not a member of ‘std’
2 | std::println("Hello, world!");
| ^~~~~~~
main.cpp:1:1: note: ‘std::println’ is defined in header ‘<print>’; this is probably fixable by adding ‘#include <print>’
+++ |+#include <print>
1 | int main() {GCC even suggests the fix: add #include <print>.
#define
#define tells the preprocessor to replace a name with some text, everywhere after that line:
#include <print>
#define MAX_SCORE 100
int main() {
std::println("The top score is {}", MAX_SCORE);
}Output
The top score is 100
The compiler never sees MAX_SCORE; by the time it reads the code, the preprocessor has already put 100 there.
Modern C++Prefer constants to #define
Because #define replaces text blindly, it ignores the rules the rest of C++ follows. For a named value, write constexpr int max_score = 100; instead. Variables explains constexpr. You’ll still see #define in older code and in headers.
Step 2: compiling
The compiler reads one preprocessed source file at a time, checks that it’s valid C++, and turns it into machine code in an object file (hello.o). If it can’t make sense of the file, you get a compile error, and no object file is made.
A misspelled name is the most common compile error:
#include <print>
int total_reads = 42;
std::println("{}", total_read);The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:4:20: error: ‘total_read’ was not declared in this scope; did you mean ‘total_reads’?
4 | std::println("{}", total_read);
| ^~~~~~~~~~
| total_readsThe message starts with the file name, the line and the column, then says what’s wrong; GCC even asks whether you meant total_reads. When there are many errors, fix the first one and build again: later errors are often caused by the first.
Declarations and definitions
The compiler reads a file from top to bottom, so it must hear about a name before the name is used. A declaration tells it the name and its type. A definition gives the body.
#include <print>
int square(int x); // declaration: the name and its type
int main() {
std::println("{}", square(12));
}
int square(int x) { // definition: the body
return x * x;
}Output
144
int square(int x) is a function called square that takes a whole number x and returns a whole number. Functions covers functions in full. Here, the declaration on line 3 is all the compiler needs to check the call in main: the name exists, it takes an int, and it returns an int.
Step 3: linking
A declaration is a promise: “this function is defined somewhere”. The compiler trusts it. When it compiles a call to square, it leaves a note in the object file: “needs square(int)”. The linker keeps that promise. It joins all the object files, finds the definition of every name that’s needed, and makes the executable.
If no object file has the definition, the linker stops with a link error. This file compiles, but it can’t be linked into a program:
#include <print>
int square(int x);
int main() {
std::println("{}", square(12));
}The compiler rejects this
ld: main.o: in function `main': main.cpp: undefined reference to `square(int)' collect2: error: ld returned 1 exit status
Notice where the message comes from: ld is the linker, and collect2 is the part of GCC that runs it. A link error doesn’t point at a line you wrote, because no single line is wrong. The definition is missing.
Building a program from two files
In a real project, the definition usually lives in another source file. Put it in square.cpp:
int square(int x) {
return x * x;
}
Then compile each file to an object file, and link the two together:
g++ -std=c++23 -c main.cpp -o main.o
g++ -std=c++23 -c square.cpp -o square.o
g++ main.o square.o -o app
./app
This time the linker finds square in square.o, and ./app prints 144. You can also pass both source files to one command, g++ -std=c++23 main.cpp square.cpp -o app: g++ preprocesses and compiles each file, then links them both.
Why compile separately? A big program has hundreds of source files. When you change one, only that one needs compiling again; the linker reuses every other object file. Build tools such as CMake, which Setting up introduces, do this bookkeeping for you.
Rules of thumb
| Kind of error | Which step | What the message looks like | Usual fix |
|---|---|---|---|
| Compile error | Compile | file.cpp:4:20: error: ... with a line and a column | Fix that line, or add the missing #include |
| Link error | Link | undefined reference to ..., from ld | Define the function, or add the file that defines it to the build |
- Read the first error first, and check which step it came from.
- Declare a function before you call it. Define it exactly once in the whole program.
- When a build fails, there’s no new executable. Fix the error before you run the program again.
Under the hood
An object file holds machine code plus a table of names called symbols: the ones the file defines and the ones it still needs. The nm tool lists them (-C shows names the way you wrote them):
nm -C square.o
nm -C main.o | grep square
For square.o, nm prints T square(int): T means “defined here, in the code”. For main.o, it prints U square(int): U means “undefined: needed from somewhere else”. Linking is matching every U to exactly one T.
Without -C, the name in square.o is _Z6squarei. The compiler encodes the parameter types into the name the linker sees, so square(int) and a square(double) are different symbols. That detail matters in the pitfall below.
Common pitfalls
The declaration doesn’t match the definition
The declaration says square takes a double (a number with a fractional part), but the definition takes an int. To the linker these are two different functions, and the one main calls doesn’t exist:
#include <print>
int square(double x);
int main() {
std::println("{}", square(1.5));
}
int square(int x) {
return x * x;
}The compiler rejects this
ld: main.o: in function `main': main.cpp: undefined reference to `square(double)' collect2: error: ld returned 1 exit status
The fix is to make the declaration and the definition agree on the return type and the parameter types: both int square(int x), or both int square(double x).
Running an old executable after a failed build
If the build fails, the old hello from your last successful build is still in the folder. Run it, and you’re testing code you’ve since changed. Join the two commands with &&, which runs the second only if the first succeeds:
g++ -std=c++23 hello.cpp -o hello && ./hello
Common pitfallForgetting a file on the command line
g++ -std=c++23 main.cpp -o app gives the same undefined reference error as the example above, even if square.cpp is right there in the folder. The linker only sees the files you give it.
Try it yourself
Try it yourself
Add a function cube that returns x * x * x. Declare it above main, define it below main, and print cube(3) after the square.
#include <print>
int square(int x);
int main() {
std::println("square: {}", square(3));
}
int square(int x) {
return x * x;
}Expected output
square: 9 cube: 27
Show a hint
Copy the pattern of square: a declaration line above main, and a definition with a body below main. Then add a second std::println call.
Show a solution
#include <print>
int square(int x);
int cube(int x);
int main() {
std::println("square: {}", square(3));
std::println("cube: {}", cube(3));
}
int square(int x) {
return x * x;
}
int cube(int x) {
return x * x * x;
}The declaration lets the compiler check the call to cube in main. The definition gives the linker the code to connect that call to. Leave out the declaration and you get a compile error (cube was not declared); leave out the definition and you get a link error (undefined reference to cube(int)).
Saved in this browser only.