Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an extern "C" declaration work?

Tags:

c++

c

extern-c

I'm taking a programming languages course and we're talking about the extern "C" declaration.

How does this declaration work at a deeper level other than "it interfaces C and C++"? How does this affect the bindings that take place in the program as well?

like image 259
samoz Avatar asked Mar 08 '10 17:03

samoz


People also ask

How does C extern work?

Software Engineering C Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files.

What is extern in C with example?

“extern” keyword is used to extend the visibility of function or variable. By default the functions are visible throughout the program, there is no need to declare or define extern functions. It just increase the redundancy. Variables with “extern” keyword are only declared not defined.

What does extern C mean in C?

The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.) extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block.

What is the use of extern C in C++?

The extern “C” keyword is used to make a function name in C++ have the C linkage. In this case the compiler does not mangle the function.


1 Answers

extern "C" is used to ensure that the symbols following are not mangled (decorated).


Example:

Let's say we have the following code in a file called test.cpp:

extern "C" {   int foo() {     return 1;   } }  int bar() {   return 1; } 

If you run gcc -c test.cpp -o test.o

Take a look at the symbols names:

00000010 T _Z3barv

00000000 T foo

foo() keeps its name.

like image 98
Bertrand Marron Avatar answered Sep 27 '22 18:09

Bertrand Marron