Wednesday, 3 December 2014

What is name mangling in C++ and explain with example?

What is name mangling in Cpp?

C++ compilers differentiates the functions when it generates the object code. It adds the additional information to the function names called as 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 functions with same name and differences in parameters. To differentiate the functions name mangling should be used.
Let us see consider following declarations of function fun()

int  fun (void) { return 1; }

int  fun (int)  { return 0; }

void g (void) { int i = fun(), j = fun(0); }

A C++ compiler may mangle above names to following

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 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 extern “C” block. C++ compiler makes sure that names inside extern “C” block are not changed.

No comments: