Name mangling is a way to assign different names to the overloaded functions in c++. we know function overloading in c++ provides a way by which we can declare more than one  functions with the same name with different arguments. This is called function overloading and c++ manage these function with name mangling. To learn about function overloading learn the following link http://wikistack.com/function-overloading-c/.

Let Us see the declaration of function with name sum in below code.

#include<iostream>
using namespace std;

void sum( int a, int b);
int sum( float a, float b);
void sum(int a,float b);
int main()
{
int a=5;
int b=6;
float c = 3.2;

sum(a, b);
sum(c , c);
sum(b, c);
return 0;
}

void sum( int a, int b)
{
a = a + b;
cout<<a<<endl;
}
int sum (float a, float b)
{
a= (a + b);
cout<<a<<endl;
return static_cast<int>(a);
}
void sum( int a, float b)
{
float c = a + b;
cout<<c<<endl;
}

Note:

In above example the function sum is simple function (not virtual function ). The simple functions always get called by their names only. As the overloaded version of function ( sum as in above example) has same name then how does different version of overloaded function gets called? This is achieved by the help of compiler. c++ compiler changes the name of all the function definition and calls while compiling the program. This is called name mangling in c++.

  • C++ always do name mangling of all functions including overloaded functions.
  • Name mangling can be prevented by by extern keyword.

How to see mangled name

We can generate assembly code of above example to see the mangled name of overloaded function sum.

(1) Run Below command on Linux Terminal

#g++ -S examle.cpp

This will generate example.s file.

(2) Run below command to see mangled name in assembly code.

# grep sum example.s

After this we would get output like below.

.type    _Z3sumii, @function
_Z3sumii:
.size    _Z3sumii, .-_Z3sumii
.globl    _Z3sumff
.type    _Z3sumff, @function
_Z3sumff:
.size    _Z3sumff, .-_Z3sumff
.globl    _Z3sumif
.type    _Z3sumif, @function
_Z3sumif:
.size    _Z3sumif, .-_Z3sumif

How to prevent name mangling in c++?

If we want to prevent name mangling then we have to declare function as extern “C” . For example in below code the function print declared with extern “C” will tell the compiler that it is c style function hence compiler will not mangle the name for it.

#include<iostream>
using namespace std;

extern "C" void print()
{
        cout<<"not mangled"<<endl;
}
void print(int a)
{
         cout<<a<<endl;
}
int main()
{
     return 0;
}


Related Contents to follow