mixing C and C++

Started by
2 comments, last by MindCode 20 years, 9 months ago
I''ve seen and used this many times before: #ifdef __cplusplus extern "C" { #endif To tell the compiler to get out of C++ and go pure C, but can it be done the other way around? #ifndef __cplusplus extern "C++" { #endif If so then can I define functions declared in the C code from within the C++ code? Esentially just masking a bunch of oop from the rest of a C++ program. If this won''t work then will GCC let me link a C++ object file with a C object file? Or is there some difference in the way the languages are compiled that makes it impossible.
That's just my understanding; I could be wrong.
Advertisement
extern "C" doesn''t tell the compiler to "get out of C++". It is still compiling C++ as C++, all that changes is the way symbol names are decorated. Because C++ allows function overloading, when the compiler converts your code into assembly, it has to ''mangle'' the symbol names, in order to include information about return types, argument lists, namespaces, and so on. The extern "C" simply tells the compiler not to perform this mangling, and instead generate decorated names the "C way".

extern "C++" is valid, but only in a C++ file, AFAIK. That will merely ''turn the mangling on.''
So no, C compilers will not understand

extern "anything"
please note there is also PASCAL linkage in most compilers ... because pascal and C have different rules over who is supposed to clean the stack on function exit ... and yes C compiler support the pascal linkage rules (many of them, I don''t believe it is standard though) ... someone who knows about this, please post.

C++ linkage of course is not supported in C, as two things prevent this:

1 - C linkage is official, C++ has no official standard type of mangling, so there can be no compatible C++ linkage spec.

2 - C is fundamentally simpler than C++, and so would, by definition of compiling in C mode, would not be away of the state of overloading etc for function, because such do not exist, and so the mangling would not exist.

But this is not really an issue, because C++ supports native C linkage, and so that is the common ground, to attempt to add C++ linkage to C gains nothing that isn''t already possible using C linkage in C++.

This topic is closed to new replies.

Advertisement