Home > Article > Backend Development > Name confusion and extern "C" in C++
In C we can use the function overloading feature. Using this feature, we can create functions with the same name. The only difference is the type of parameters and the number of parameters. The return type is not considered here. Now the question is, how does C differentiate between overloaded functions in object code?
In the target code, it changes the name by adding information about the parameters. The technique applied here is called name mangling. C There is no standardized name mangling technique. Therefore different compilers use different techniques.
The following is an example of name mangling. The overloaded function is named func(), and there is another function my_function().
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 compilers will change it like below -
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 }
C does not support function overloading, so when we When linking C code in C, we must ensure that the names of symbols do not change. The following C code will generate an error.
int printf(const char *format,...); main() { printf("Hello World"); }
undefined reference to `printf(char const*, ...)' ld returned 1 exit status
The problem occurs because the compiler changes the name of printf(). And it doesn't find the updated definition of printf() function. To solve this problem we have to use extern "C" in C. The C compiler ensures that function names are not mangled when some code is used within this block. So the name won't change. So the above code will look like this to solve this problem.
extern "C" { int printf(const char *format,...); } main() { printf("Hello World"); }
Hello World
Note: These code blocks may produce different results in different compilers.
The above is the detailed content of Name confusion and extern "C" in C++. For more information, please follow other related articles on the PHP Chinese website!