Home  >  Article  >  Backend Development  >  Name confusion and extern "C" in C++

Name confusion and extern "C" in C++

WBOY
WBOYforward
2023-08-29 10:21:111300browse

名称混淆和extern "C"在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().

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 compilers 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
}

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.

Example

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

Output

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.

Example

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

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete