Mohamed Iqzas
Mohamed Iqzas

Reputation: 1046

difference between extern "C" and simply extern

I have seen C/C++ code using extern "C" declared in function signatures and also while including a C header into a CPP file.

but some functions just declare extern before their signature(without the "C").

QN1:

are these both ways of defining functions have same effect or do they imply different things?

sorry if I am very silly but I am not able to find this difference through Google.

Eg:

extern int someFunction( void *ret_val);

extern "C" int someFunction( void *ret_val);

QN2:

if a function is declared with an extern in its signature, is it necessary for the corresponding header file to be included inside a extern "C" block?

As pointed by another user in comments, the marked duplicate does not fully satisfy the question here. I am editing so that in future others may not be mislead into a different question.

Upvotes: 8

Views: 4120

Answers (3)

ha9u63a7
ha9u63a7

Reputation: 6824

The presence of extern "C" in a C++ file is a personal intent to disable name-mangling transformation that the C++ compiler does to the functions in that file. When there is no name-mangling, then a client C code can call these functions. This is done when you have a mixture of C/C++ code and you need to keep track of language-specific features. In a bit more geeky way, the C linkage becomes compatible in presence of a Cpp compiler.

The code could be anything from a variable/typedef to a full function/module declaration.

But if you do this:

extern char c; // same goes true for extern int foo()

it means that you are saying "I am using char c, which has a declaration external to this file". More like in another module somewhere in the search-path. This is implicitly global. In runtime, if c changes, the change is reflected everywhere. This is provided that your compiler directives such as -Iinclude_file_dirs -Ssource_file_dirs etc. are provided correctly (on GCC or g++). Using a powerful IDE such as Visual Studio 2010 or later, you can do these very easily.

"extern" is a linkage keyword. You can combine it with "C" for compiler-specific linkage directives.

Upvotes: 2

lowtech
lowtech

Reputation: 2582

extern "C" disables name mangling. It will allow your C++ code to call functions from library compiled by C compiler

Upvotes: 7

haccks
haccks

Reputation: 106012

extern "C" int someFunction( void *ret_val);  

will make someFunction have C linkage.

Upvotes: 4

Related Questions