Name Mangling in C++
In C++ we can write multiple functions of same name with different parameter type is call function overloading. To achieve function overloading c++ uses a concept know as "name mangling".
For differentiating the function name c++ compiler change the function name by adding information about arguments
actual function prototype: void show(int arg)
After name mangling: void show_i(int arg)
actual function prototype: void show(float arg)
After name mangling: void show_f(float arg)
Here the function show(int) & show(float) changes to show_i(int) & show_f(float)
Actually in developer think that he/she is calling show function but compiler changer that show to show_i or show_f according to the arguments.
C doesn't support "name mangling"; so we can't call c function in c++ project.
To call c function in c++ "extern" key word is used.
How do we call C function from C++
Ans: Suppose we have 2 files main.cpp & add.c
C File
------------------add.c-----------------------
void f(int i)
{
printf("I am in f=%d",i);
}
int g(double d)
{
printf("I am in g=%lf",d);
}
--------------------------------------------------------
C++ File
----------------------main.cpp-----------------------
extern "C" void f(int); // one way
extern "C" { // another way
int g(double);
double h();
};
void code(int i, double d)
{
f(i);
int ii = g(d);
// ...
}
-----------------------------------------------
We can include header files in this way as well
extern "C" {
// Get declaration for f(int i, char c, float x)
#include "my-C-code.h"
}
How do we call C++ function from C
Ans: Calling function f & g from c code
C File
-----------------------main.c-----------------------
void code(int i, double d)
{
f(i);
int ii = g(d);
// ...
}
-----------------------------------------
C++ File
----------------------add.cpp-----------------------
extern "C" void f(int); // one way
extern "C" { // another way
int g(double);
double h();
};
void f(int i)
{
printf("I am in f=%d",i);
}
int g(double d)
{
printf("I am in g=%lf",d);
}
----------------------------------------------
Comments
Post a Comment