Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Name Mangling and extern "C" in C++
In C++, function overloading allows multiple functions with the same name but different parameter types or numbers. However, this creates a problem: how does the compiler distinguish between these functions in the object code? The solution is a technique called name mangling.
Syntax
extern "C" {
// C function declarations
}
What is Name Mangling?
Name mangling is a technique where the compiler modifies function names by adding information about parameters to create unique identifiers. C++ has no standardized name mangling scheme, so different compilers use different approaches.
Example: Function Overloading
Here's how overloaded functions appear in source code −
#include <stdio.h>
int func(int x) {
return x * x;
}
double func(double x) {
return x * x;
}
int main() {
int result1 = func(5); // calls int version
double result2 = func(2.5); // calls double version
printf("Integer result: %d\n", result1);
printf("Double result: %.2f\n", result2);
return 0;
}
Integer result: 25 Double result: 6.25
How Name Mangling Works
The compiler might transform the above functions into something like this internally −
int __func_i(int x) // mangled name for int version double __func_d(double x) // mangled name for double version
Problem with C Functions
C does not support function overloading and doesn't use name mangling. When linking C code with C++, this creates issues. The following code will fail −
int printf(const char *format, ...);
int main() {
printf("Hello World");
return 0;
}
undefined reference to `printf(char const*, ...)' ld returned 1 exit status
Solution: Using extern "C"
The extern "C" directive tells the C++ compiler to use C linkage, preventing name mangling −
extern "C" {
int printf(const char *format, ...);
}
int main() {
printf("Hello World\n");
return 0;
}
Hello World
Key Points
- Name mangling enables function overloading by creating unique identifiers.
- Different compilers use different mangling schemes.
- Use
extern "C"when interfacing C++ with C libraries. - C functions inside
extern "C"blocks cannot be overloaded.
Conclusion
Name mangling is essential for C++ function overloading, but extern "C" is necessary when linking with C libraries. This ensures compatibility between C and C++ code by preventing name mangling for C functions.
