Name Mangling and extern “C” in C++


In C++ we can use the function overloading feature. Using this feature, we can create functions with same name. The only difference is the type of the arguments, and the number of arguments. The return type is not considered here. Now the question comes how the C++ distinguishes overloaded functions in object code?

In the object code, it changes the name by adding information about the arguments. The technique which is applied here is called the Name Mangling. C++ has no standardized technique for name mangling. So different compiler uses different techniques.

Here is an example of Name Mangling. The overloaded functions are named as func(), and another function my_function() is there.

Example

int func(int x) {
   return x*x;
}
double func(double x) {
   return x*x;
}
void my_function(void) {
   int x = func(2); //integer
   double y = func(2.58); //double
}

Some C++ compiler will change it like below −

Example

int __func_i(int x) {
   return x*x;
}
double __func_d(double x) {
   return x*x;
}
void __my_function_v(void) {
   int x = __func_i(2); //integer
   double y = __func_d(2.58); //double
}

The C does not support function overloading, So we have to make sure that name of a symbol is not changed, when we link a C code in C++. The following C++ code will generate an error.

Example

int printf(const char *format,...);
main() {
   printf("Hello World");
}

Output

undefined reference to `printf(char const*, ...)'
ld returned 1 exit status

This problem is generating because the name of the printf() is changed by the compiler. And it does not find the definition of the updated printf() function. To overcome this problem, we have to use the extern “C” in C++. When some code is used inside this block, then C++ compiler ensures that the function name is unmangled. So the name will not be changed. So the above code will be like this to solve this problem.

Example

extern "C" {
   int printf(const char *format,...);
}
main() {
   printf("Hello World");
}

Output

Hello World

Note: These block of codes may generate different results in different compilers.

Updated on: 30-Jul-2019

799 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements