On Thu, Dec 18, 2008 at 7:14 AM, Rodolfo kix Garcia <[email protected]> wrote:
> Pietro Gagliardi escribió:
>> extern "C"{
>> #include <9p.h> // or whatever you do
>> }
>>
>> you can link 9p into a C++ program easily.
>
> If I use the extern "C" it compiles :'-)
>
> Using "extern function" is not valid for linking C and C++


 extern works fine between C and C++, but maybe it doesn't do what you
think it does. extern assures the compiler that there is a symbol with
a certain type defined in some other object than the one currently
being compiled.
 What you're running into is a name mangling issue. C++ supports
overloaded functions, ie. functions with the same name but different
prototypes. This doesn't fly with the linker, because as far as it is
concerned each symbol has a unique type[1]. So, C++ mangles[2] the
function name by appending a string representation of the prototype.
int main(int, char**) maps to a symbol like main_i_i_ppc. The mangled
notation is compiler specific of course.
 This presents a problem for interoperation with C code. Any existing
library compiled by a C compiler has regular non-mangled names. But, a
C++ compiler will grab the prototypes from the library's header file,
and then tell the linker to look for mangled versions of the symbols.
Obviously it is not going to find them.
 So, as a workaround, C++ overloads the extern keyword to allow the form:
extern "C" {
...
}
 Which tells the compiler "the functions defined in this block were
compiled with a C compiler, don't mangle the symbols".

[1] Does the linker actually know about types or just sizes?
[2] "mangles" is official terminology, so at least they're honest about it. ;)

-sqweek

Reply via email to