Explaining the use of extern “C” in C++

The extern keyword is used to define global variables. Global variables are also known as external variables. They are defined outside the function. The value of these variables can be modified using functions. Also, they can be used throughout the program. In this post, we will discuss the use of extern C in C++.

It is used in C++ programming while declaring a function compiled in C language. Compilers use different linkage schemes for C++ functions as compared to C functions. C++ supports function overloading by using name mangling to create the actual function name in object files.

However, if you compile a C file using a C compiler its object file will not have function names mangled, and errors will be displayed if we attempt to call functions from C++. The extern “C”, tells the C++ compiler that functions with declarations in the extern “C” block won’t be name-mangled. Hence the problem is fixed.

Here’s an example given:

int printf(const char *format,...);
void main()
{
 printf("Example code snippet");
}

Save it, compile it and run it with a C++ compiler, the following error will be displayed

/tmp/cc34cVoT.o: In function `main':
a.cpp:(.text+0xf): undefined reference to `printf(char const*, ...)'
collect2: ld returned 1 exit status

This error is shown because of the name of “printf” is changed by the C++ compiler and it was not able to find the definition for it.
When we add extern “C” :

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

void main()
{
 printf("Example code snippet");
}

Summarizing the article, function names may or may not be changed in C language as it doesn’t support function overloading concept. Thus, to refrain from linking problems, C++ supports the concept of extern “C”.

I hope, you have understood what is the usage of this concept.

Mention below your comments, if you find any mistake in the article or to share more information related to the topic of this article.

You may also learn,

Storage classes in CPP

Leave a Reply

Your email address will not be published. Required fields are marked *