top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+7 votes
338 views

In lot of C++ code in my company I see extern C code something like

extern "C"
{
    int sum(int x, int y)
    {
        return x+y;
    }
}

Please explain the significance of this?

posted Apr 27, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

When you write a C++ program and compile the program using the g++ compiler, it does name mangling which is related to somewhat function overloading concept. By putting the code within the extern "C" { } block, does not allow g++ compiler to do name mangling for functions written in C .

answer Apr 27, 2016 by Harshita
Harshita,
i created 2 function with same name and different number of arguments,
1 function i put it into extern "C" and other outside of it,
While compiling it i am able to compile and run it.
Can you please tell me where i am making mistake to understand extern "C"?
Similar Questions
+2 votes

I tried using -Wzero-as-null-pointer-constant in a C++ program, but I got warnings in some C headers, even though they are wrapped in extern "C" blocks.

Since there is no nullptr in C, wouldn't it make more sense to disable the warning within those blocks? Is there some option that I'm missing?

+1 vote

I have an oversight in my code where I'm declaring & defining a function
with C-linkage, though it's not possible.

Example snippet:

#ifdef __cplusplus
extern "C"
{
#endif

// ... some functions which are compatible with C linkage

// Intended to be a helper function not exposed from library
std::string GetEngineVersion()
{
 // ...
}

#ifdef __cplusplus
}
#endif

Obviously the GetEngineVersion function cannot have C linkage because it returns a C++ class.

My question is: does GCC have a warning for this scenario? Specifically, can it warn when something is declared extern "C" that's incompatible with C linkage?

I compile with the following warning flags and I didn't get a warning:

-Wall -Wunused-parameter -Wextra -Weffc++ -Wctor-dtor-privacy
-Wnon-virtual-dtor -Wreorder -Wold-style-cast -Woverloaded-virtual
-Werror

Incidentally, when I compile the same code in VS2013 I get this warning:

warning C4190: 'GetEngineVersion' has C-linkage specified, but returns UDT 'std::basic_string' which is incompatible with C
...