×

Name Mangling and extern in C++

Name Mangling and Function Overloading:

Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the same name. Function overloading cannot be understood by lower-level languages (such as C or assembly) or tools (such as linker). Each function name in these languages must be distinct for functions to be distinguishable from one another solely by name.

Functions are distinguished in C++ using both their name and parameters. For each function, a brand-new name is generated. The original C++ function's name and parameters determine the new name. It will always produce a unique name when given the name of a function and a set of parameters.

Even if the original C++ function name remains the same, if parameters (number of parameters, type of parameters, or order of parameters) change, a new name will be generated. Name mangling is the term used to describe this encoding of the function name.

The name-mangling method is compiler-dependent. Compilers can employ a variety of tactics. A name that has been distorted by one compiler might not have been distorted by other compilers.

Take into account the following Name Mangling example, which contains several f() function declarations:

// To demonstrate function overloading 
// Name Mangling
int fun(void) 
{ 
return 0; 
}
 
int fun(int) 
{ 
return 1; 
}
 
void good(void)
{ 
int i = fun(), j = fun(0); 
}

We can easily see that the above two functions, which have the same name, "fun," but the parameter is different, then the compiler will generate a new name for differentiating between the same functions, but the parameter will be the same which prevents naming conflicts and makes it possible to overload functions or variables with the same name.

The names listed above may be altered by some C++ compilers to become,

// To demonstrate function overloading 
// Name Mangling
 
int __fun_v(void) 
{ 
return 0; 
}
 
int __fun_i(int) 
{ 
return 1;
 }
 
void __good_v(void) 
{ 
int i = __fun_v(), j = __fun_i(0);
 }

Explanation:

  • In the above functions, we can easily see that compiler is generated a new name for functions which is not similar.
  • Before the compilation, Previously the 1st function name was "fun", but after the compilation, the function name is changed from "f" to "__fun_v”.
  • Similar things happen in the 2nd function and 3rd function that compiler generates the function name with the same arguments when this program is compiled.
  • So this is called Name Mangling.

Note: function overloading is not supported in C, care must be taken to ensure that no symbol names are modified while linking C code to C++.

Extern “C” in C++:

Extern "C" is a keyword in C++ that is used to indicate that the following function or variable should not be mangled. This allows C++ code to interoperate with C code, as C code does not use name mangling. When a function or variable is declared with extern "C", its name will remain the same as it would in C, making it accessible to C code.

When code is placed in the extern "C" block, the C++ compiler makes sure the function names are preserved and that the compiler emits a binary file with the names of the functions unaltered, just like a C compiler would.

In order to prevent C++ functions from being altered so that they can be called from C, the extern "C" linkage specifier can also be used.

For example, consider the following C++ code:

int add(int a, int b) 
{
    return a + b;
}

Without extern "C", the compiler would mangle the name of the function "add" to include information about its type and other attributes, such as the number and types of its parameters. This would make the function difficult or impossible for C code to call.

To prevent this, the function can be declared with extern "C" like this:

extern "C" int add(int a, int b) 
{
    return a + b;
}

This tells the compiler not to mangle the name of the function, and it will remain the same as it would in C. This makes it accessible to C code and can be called from C code without any issues.

Extern "C" is often used in header files shared between C++ and C code. For example, a C++ library might define several functions with the extern "C" in a header file, which can then be included in C code and used without any issues.

It's worth noting that extern "C" applies only to the function or variable that immediately follows it, and it's not a storage class specifier like extern, static or auto. It's also important to note that while extern "C" works for both functions and variables, not all C compilers support it.

Conclusion:

  • Since C++ allows for function overloading, extra information must be added to function names (a process known as name mangling) in order to prevent conflicts in binary code.
  • Name mangling is a technique used in C++ to encode the information about a function or variable's type, scope, and other attributes in its name, which allows the compiler to generate unique names for functions or variables that have the same name but different types or scopes.
  • Since function overloading is not supported by C, function names cannot be modified. The extern "C" block is supported by C++ to prevent linking issues. The extern "C" block's names are protected from alteration by the C++ compiler.
  • Extern "C" is a keyword in C++ that is used to indicate that the following function or variable should not be mangled, making it accessible to C code and allowing C++ code to interoperate with C code. It's a useful technique for creating libraries that can be used by both C and C++ code.

Related Topics

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods,...

4 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

2 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

3 minutes read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Print Table Using Do while Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.