Linker
- C++ course
- Expert
- Lesson 40/47
- 5 min
Learn the linker and linking process.
Linker
The linker combines compiled object files (.o) into an executable. Each object file carries a symbol table; this table lists defined and referenced symbols.
The linker's job is to find a definition for every referenced symbol. If the definition is in another file, the linker takes it from there and points the reference to the real address. If no definition is found, an undefined reference error is raised. This is why large projects split into multiple .cpp files; each compiles separately and they link together.
Symbol resolution
If a .cpp file calls compute but does not define it, the object file keeps an undefined reference mark for compute. The linker searches other .o files for the definition of compute.
If found, the linker points the reference to the real address. If not found, it raises undefined reference to compute. This is why a forward declaration (int compute(int);) goes in a header; the definition goes in a .cpp file. Each file does not see the definition while compiling but the linker resolves it.
Practice Write the compute function
Write int compute(int x) with body return x * 2;. In main write std::cout << compute(5);.
Starter code
#include <iostream>
// Define the compute function here
int main() {
// Call compute and print it
return 0;
}Sample solution
#include <iostream>
int compute(int x) {
return x * 2;
}
int main() {
std::cout << compute(5);
return 0;
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the linker do?
g++ main.o utils.o -o program- Compiles source code
- Starts the operating system
- Garbage collects
- Combines object files and resolves symbols Correct answer
Explanation: The linker combines .o files and produces an executable.
2 Complete the forward declaration
int compute(int ____); // forward declaration
int compute(int x); // forward declaration
Explanation: int compute(int x); is a forward declaration.
3 Match each concept to its role
| Term | Meaning |
|---|---|
undefined reference |
Link error |
object file (.o) |
Symbol table |
symbol table |
Symbol addresses |
linker |
Combines objects |