Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ to Java conversion question about extern "C"

Tags:

java

c++

c

I have to convert some C/C++ code to Java. My C++ is extremely rusty.

In a .h file, I have the following:

#ifdef __cplusplus
extern "C" {
#endif

/* tons of declarations */

#ifdef __cplusplus
} /* extern C */
#endif

What is the use of extern "C"? What does it mean? Is it telling the compiler that corresponding code should be interpreted as pure C, rather than C++?

EDIT

Thanks for the answers so far. The history of the code I have to convert is that it seems like a part was written in C first, then the rest was written in C++. So my header file seems to correspond to 'old' C code.

I'll convert this code into a public final class with static method and attributes. No overriding.

like image 834
Jérôme Verstrynge Avatar asked Jun 30 '11 21:06

Jérôme Verstrynge


People also ask

When should I use extern 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.

Do C++ features are allowed in extern C block?

Not any C-header can be made compatible with C++ by merely wrapping in extern "C".

Why do we need extern C?

Using extern "C" lets the compiler know that we want to use C naming and calling conventions. This causes the compiler to sort of entering C mode inside our C++ code. This is needed because C++ compilers mangle the names in their symbol table differently than C compilers and hence behave differently than C compilers.

Is extern supported in C?

extern "C" and extern "C++" function declarations In C++, when used with a string, extern specifies that the linkage conventions of another language are being used for the declarator(s). C functions and data can be accessed only if they're previously declared as having C linkage.


1 Answers

It's telling the compiler that function signatures should be C compatible. Name mangling are different in C and C++ (i.e. C++ supports method overloading while C does not) so in order to make some function calls (i.e. some DLL dynamic calls) compatible with C signature, you use extern C in C++ code.

Take a look at this StackOverflow question for a great explanation on the topic.

like image 152
Pablo Santa Cruz Avatar answered Sep 23 '22 11:09

Pablo Santa Cruz