Compilation vs.
Linker Errors
Learn to interpret and distinguish the two main categories of build errors in C++: errors caught by the compiler and errors caught by the linker.
What Happens When You Build?
When you press "Build" or run g++ main.cpp, your code passes through several stages before becoming an executable. Each stage can produce its own type of error.
What Is a Compilation Error?
A compilation error (also called a compiler error) occurs when the compiler cannot translate your source code into machine instructions. The compiler checks each .cpp file independently.
What Is a Linker Error?
A linker error occurs after all files compile successfully. The linker tries to combine object files into one executable, and fails when it cannot find or reconcile symbol definitions.
The Core Rule
Declaration vs. Definition
Understanding the difference between a declaration and a definition is the key to understanding linker errors. The compiler only needs declarations; the linker needs definitions.
Key Distinction: Same Symptom, Different Cause
Both error types can involve the same function name, but the root cause is completely different. Knowing which tool produced the message tells you where to look.
| Compilation Error | Linker Error | |
|---|---|---|
| When | During compile step | After all files compile |
| Cause | Broken syntax or types | Missing or duplicate definition |
| Scope | Single .cpp file | Across all .cpp files |
| Typical keyword | error: expected, undeclared | undefined reference to |
| Fix involves | Editing the flagged line | Adding a missing file or library |
How to Diagnose Build Errors
Example 1: Compilation Error
Example 2: Undeclared Identifier
Example 3: Linker Error
Example 4: Multiple Definition
Anatomy of an Error Message
Common Mistakes
Summary Comparison
| Compilation Error | Linker Error | |
|---|---|---|
| Tool | g++ (compiler) | ld (linker) |
| Phase | Translation (per file) | Linking (all files) |
| Reports | File, line, column | Symbol name only |
| Common causes | Typos, missing ; , type mismatch | Missing definition, missing library |
| Fix strategy | Edit the flagged line | Add missing .cpp or -l flag |
| Needs declaration? | Yes, to compile | Yes, plus a definition |
Question 1 of 5
You see the error message: "undefined reference to `calculateArea()'". What type of error is this?
Question 2 of 5
Which of the following would most likely cause a compilation error rather than a linker error?
Question 3 of 5
A student writes a function declaration void printScore(int s); in a header file, but never writes the function body in any .cpp file. What happens?
Question 4 of 5
You see an error that includes a file name, line number, and column number. This error was most likely produced by the:
Question 5 of 5
A program has 15 error messages. After fixing only the first error (a missing closing brace), the program recompiles with zero errors. What does this demonstrate?