Sunday, 29 March 2015

Extern Keyword and Alternate linkage specifications in C++

Extern Keyword and Alternate linkage specifications in Cpp:

In C++ compiler construction, name mangling  or name decoration is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.

Name mangling provides a way of encoding additional information in the name of a function, structure, class or another data type in order to pass more semantic information from the compilers to linkers.

If the function is like below
 float myFunc (int a, char b); 

The compiler will produce the code for the above function may be like this
 _ myFunc _int_char

If we want to run the code using standard C, we have to write function like below.
extern "C" float myFunc (int a, char b)

This tells the compiler to give C linkage to myFunc ( ) so that the compiler doesn't decorate the name. The only two types of linkage specifications supported by the standard are “C” and “C++,” but compiler vendors have the option of supporting other languages in the same way.

See the sample code below to avoid the name mangling for
extern "C" {
float MyTestFun (int a, char b);
double dMyTestFun2 (int a, char b);
For the header file
extern "C" {
#include "MyLib.h"

Most of the C++ compilers handle the alternate linkage specifications inside their header files that work with both C and C++.

No comments: