What is the effect of extern C in C++?

Overview

In C++, the extern C keyword is used to make a function name that has a link with C. This is a case when the compiler doesn’t mangle the function. Before we continue, let’s talk about the mangling first.

Mangling

We can have the feature of a function overloading, which we can use to create the function with the same name but with different types of arguments and datatypes.

Note: We have to think about how the compiler distinguishes between the overloaded functions?

In the object code, it changes its name by adding information about the arguments. This is known as name mangling. Different compilers have different techniques for doing this.

Let’s have a look at the example to understand the concept.

int temp(int val) { return val; }
float temp(float val) { return val; }
double temp(double val) { return val; }

void function(void) 
{
   int x = temp(21); 
   float y = temp(2.1);
   double z = temp(3.19); 
}

Some of the C++ compiler will mangle the above, as shown below:

int __temp_i(int val) { return val; }
float __temp_f(float val) { return val; }
double __temp_d(double val) { return val; }
 
void __function_v(void) 
{
   int x = __temp_i(21); 
   float y = __temp_f(2.1);
   double z = __temp_d(3.19); 
}

Note: In C, there is no support for function overloading (<), so when we are linking a C code to C++, we have to make sure that the symbol name cannot be changed.

Example

int printf(const char *raw,...);
int main()
{
printf("Welcome to Educative");
}

Note: The above code produces an error because the name of the function, printf(), is changed by the compiler as the compiler is unable to find the definition for the updated printf() function.

Explanation

In order to counter this problem, we use the extern C so that the compiler makes sure that the code written inside the scope will remain unmangled. Therefore, the function’s name doesn’t change.

We have to update the existing code to this to avoid the problem.

extern "C"
{
int printf(const char *raw,...);
}
int main()
{
printf("Welcome to Educative");
}