Home > Backend Development > C++ > Name confusion and extern 'C' in C++

Name confusion and extern 'C' in C++

WBOY
Release: 2023-08-29 10:21:11
forward
1331 people have browsed it

名称混淆和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
}
Copy after login

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
}
Copy after login

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");
}
Copy after login

Output

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

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");
}
Copy after login

Output

Hello World
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template