What is the purpose of name mangling in C++?

1423 views c++
5

I've read in an article that a compiler changes the names (name mangling) of functions (that have same names) to avoid names conflict.

Consider following example.

void fun(int x)
{
    cout<<x<<endl;  
}

void fun(float x)
{
    cout<<x<<endl;
}

int main()
{
    fun(10);
    fun(10.5f);

    return 0;
}

Above is a very simple example for function overloading. Here when code is compiled the compiler will change the function name so that linker can link between two different calls.

Question: What is the need of mangling?

Since the arguments have different datatype, that could have been enough to link with proper function. Why does then, the compiler perform Name Mangling?

answered question

Because that's how the compiler can know what function has what parameters?

1 Answer

1

The linker doesn't know about overloading (it has to be generic for multiple languages). All it knows about are symbols that it needs to resolve.

The compilers name-mangling creates two different symbols for the two function overloads, allowing the linker to resolve them to the correct function.

posted this

Have an answer?

JD

Please login first before posting an answer.