Name mangling
- C++ course
- Expert
- Lesson 20/47
- 5 min
Learn name mangling and C++ symbol names.
Name mangling
Name mangling is the compiler encoding the function signature into the symbol name. Because C++ supports overloading and namespaces, the same name foo can appear multiple times; the linker needs the signature embedded in the name to tell them apart.
Example: int add(int, int) becomes _Z3addii in the Itanium ABI. Here _Z is the prefix, 3 the name length, add the name, ii two int parameters. double add(double, double) becomes _Z3adddd; different signature, different symbol.
Mangling notation
Itanium mangling codes: v=void, i=int, d=double, b=bool, c=char. The name is prefixed with its length: 3foo = foo.
Namespaces are wrapped with N...E: ns::bar() → _ZN2ns3barEv. Here N opens, 2ns is ns (length 2), 3bar is bar (length 3), E closes, v is the void parameter. Each signature maps to one symbol.
Practice Write the add function
Write int add(int a, int b) with body return a + b;. In main write std::cout << add(3, 4);.
Starter code
#include <iostream>
// Define the add function here
int main() {
// Call add and print it
return 0;
}Sample solution
#include <iostream>
int add(int a, int b) {
return a + b;
}
int main() {
std::cout << add(3, 4);
return 0;
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the body
int add(int a, int b) { return ____; }
int add(int a, int b) { return a + b; }
Explanation: Write return a + b;; the add function sums.
2 Why does C++ mangle names?
int add(int, int);
double add(double, double);- To shrink class size
- To speed up the program
- To hide the code
- For overloading and namespaces Correct answer
Explanation: Mangling separates same-named different signatures at the linker.
3 Match each signature to its mangled symbol
| Term | Meaning |
|---|---|
add(int, int) |
_Z3addii |
add(double, double) |
_Z3adddd |
foo() |
_Z3foov |
ns::bar() |
_ZN2ns3barEv |