What is name mangling in Cpp?
C++ compilers differentiate the functions when it generates the object code. It adds additional information to the function names called name mangling. Name mangling is compiler-dependent.
Why name mangling is required in c++?
As we know C++ supports function overloading, i.e., there can be more than one function with the same name and differences in parameters. To differentiate the functions name mangling should be used.
Let us see consider the following declarations of function fun()
1 2 3 4 5 |
int fun (void) { return 1; } int fun (int) { return 0; } void g (void) { int i = fun(), j = fun(0); } |
A C++ compiler may mangle the above names to following
1 2 3 4 5 |
int __fun_1 (void) { return 1; } int __fun_1 (int) { return 0; } void __g_1 (void) { int i = __fun_1(), j = __fun_1(0); } |
Following are the main points:
1. Name mangling is used to avoid conflicts in binary code.
2. Function names may not be changed in C as C doesn’t support function overloading. To avoid linking problems, C++ supports the extern “C” block. C++ compiler makes sure that names inside the extern “C” block are not changed.