In this article the keyword extern can be followed by "C" or "C++". Why would you use 'extern "C++"'? Is it practical?
The language permits:
extern "C" {
#include "foo.h"
}
What if foo.h contains something which requires C++ linkage?
void f_plain(const char *);
extern "C++" void f_fancy(const std::string &);
That's how you keep the linker happy.
There is no real reason to use extern "C++". It merely make explicit the linkage that is the implicit default. If you have a class where some members have extern "C" linkage, you may wish the explicit state that the others are extern "C++".
Note that the C++ Standard defines syntactically extern "anystring". It only give formal meanings to extern "C" and extern "C++". A compiler vendor is free to define extern "Pascal" or even extern "COM+" if they like.
I'm not sure why you would need to do it, but according to this article from Sun, you can use extern "C++" inside a block of extern "C" to specify certain functions in a group of "C" functions have the native C++ linkage.
extern "C" {
void f(); // C linkage
extern "C++" {
void g(); // C++ linkage
extern "C" void h(); // C linkage
void g2(); // C++ linkage
}
extern "C++" void k();// C++ linkage
void m(); // C linkage
}
Two guesses:
If you are in a extern "C" block, you can get C++ language linkage again by specifying a nested extern "C++".
It reserves C++ linkage, because it's the document defining C++. Who is in a better position for defining C++ language linkage than it itself. It also provides for completeness. Same deal as with signed/unsigned.
Read this answer that explains extern "LanguageName" (i.e GCC has extern "Java") aswell.
Extern "C" is answered by many. The use case for extern "C++" is when calling C++ library function in a C function. The sub-use case, that is relevant, is when linking a C++ library with a C source code with main function. Check this wiki page for more details:
C and C++ use different name mangling rules. Essentially, extern "C" tells the C++ compiler to name the function as C would name it.
This specify which link convention to use. Most languages know how to link with a "C" style function.
You need this in two cases :
A C - or other languages for that matter- program calling a function written in C++
A C++ program calling a function written in C
Example :
// declared in function.h
void f1(void);
Your C code - actually other languages are able to link with C function - will not be able to link to it because the name in the object table will use C++ convention.
If you write
extern "C" void f1(void);
Now the linking works because it uses C convention.
The #1 reason I use extern "C" is to avoid C++'s name mangling rules. This is very important if you are working in a .Net language and want to PInvoke into a particular native function. The only way to do this is with name mangling disabled.
To answer the second question, "is it practical?":
It is practical, and practically unavoidable, in standard headers like <cmath>.
Imagine a header-only library X.h, written in a common subset of C++ and C, and intended to be used from both languages. For the benefit of C++ users, X.h includes <cmath>, not <math.h>. This would not work for C users though, hadn't the authors of <cmath> sandwiched everything in extern "C++" { ... }.
Short answer is that you can use extern C to tell the compiler not to use name-mangling. This means you can link together bits of C and C++ code in the same project.
extern "C" is used to say that a C++ function should have C linkage. What this means is implementation dependant, but normally it turns off C++ name-mangling (and so overloading and strict type checking). You use it when you have a C++ function you want to be called from C code:
extern "C" void Foo(); // can be called easily from C
As for extern "C++", I've never seen it in real code, though the C++ Standard allows it. I guess it is a no-op.
Related
Is there a difference whether I use the extern "C" specifier for the entire header, or specify extern for every function?
As far as I know, there is none, since only functions and variables can be linked externally, so when I use the extern specifier before every function prototype and extern variable, I have no need to use the global extern "C" declaration!?
Example A:
#ifdef __cplusplus
extern "C" {
#endif
void whatever(void);
#endif
Example B:
extern void whatever(void);
The presence of extern "C" in a C++ file allows to call the particular C++ function from a C client caller code.
What is the difference?
A long, long time ago C-compilers generated code and addressed functions by name only.
It didn't consider parameters.
When overloaded functions were introduced in C++, extern "C" was required to specify the same name for different functions. For example void f() and void f(int) are two different functions in C++.
The C++ compiler accomplished this via name-mangling. It adds some info to the function name related to the functions parameters.
extern "C" is a command to the compiler to "refer to the older style naming convention - without mangling".
There is a difference between those two things.
The first says "the functions in here should be compiled so as to be callable from C". C++ allows multiple functions to have the same name as long as they take different arguments. C does not. To achieve that, C++ includes argument type information in the compiled name of its functions. As a result a C compiler will not be able to find the functions. If you add an extern "C" then you instead get C behaviour, but you gain the ability to call those functions from C.
The latter says "this function exists in another compilation unit". Which means that a compiler should trust that the function with that signature exists but not worry about being unable to see it. It'll be there when you link, you promise. Declarations (contrasting with definitions) are extern by default since at least C99.
This question already has answers here:
What is the effect of extern "C" in C++?
(17 answers)
Closed 8 years ago.
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.
extern "C" disables name mangling. It will allow your C++ code to call functions from library compiled by C compiler
extern "C" int someFunction( void *ret_val);
will make someFunction have C linkage.
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.
I jumped into winnt.h and I found out the code as following:
extern "C++" // templates cannot be declared to have 'C' linkage
template <typename T, size_t N>
char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N];
I'd like to ask questions as following:
how does extern "C++" work?
is this portable among GCC, and Clang?
can all templates be exported with this syntax?
With question 3, I mean that can I separate declearation and definition of the templates, and then generate a dynamic link for the template without actually give the implementation by using this trick?
Well, extern "C++" won't work in C, of course (though some compilers might support it as an extension). So it only makes sense to use it in C++.
That's because in the case of multiple nested extern linkage specifiers, the innermost one takes effect. So if you have a header file surrounded with extern "C", you can use extern "C++" to temporarily break out of it and declare something with C++ linkage.
It makes the most sense when you want to provide a generally C interface for a C++ library, but you also want to provide C++ helper bits for people actually using it in C++. So you'd put #ifdef __cplusplus \ extern "C" { \ #endif around the header as a whole, and then you ifdef-in those bits with extern "C++" to revert to C++ linkage.
It works by forcing the compiler to use C++ linkage when the surrounding code uses C linkage by default (e.g., you include winnt.h in a C program).
Yes, it should be portable.
Yes they can.
There is not much use for "extern "C++"" in C++ programs because the linkage is "C++" anyway. It makes sense to use "extern "C++"" only if there is a good chance that your C++ code will be included into a C code.
I want to implement a project in C, but it is comfortable to code some part of project in C++ and then call them from main C code.
Is it possible?! if yes, how I can do it?!
thanks in advance :)
P.S.
I used some libraries in my C++ Code such as OpenCV.
You'll need to "wrap" your C++ interface with regular C functions that take a parameter to indicate what object they'll be called on. For instance, if you have in C++
class A
{
// .. boilerplate stuff...
int SomeMethod(int n, float f);
};
Then along with it, you could declare a function such as
extern "C" int A_SomeMethod(void* Obj, int n, float f)
{
return(((A*)Obj)->SomeMethod(n, f));
}
If you're not comfortable with the casting of the void*, you can implement some kind of map from an opaque handle to an A*. But the gist is you'll need to keep around some handle/pointer to the object that the method will be called on. In order to get the pointer/handle you'll need to wrap the allocation to:
extern "C" void* A_Instantiate()
{
return new A;
}
The C++ files should be compiled separately along with the file with the functions above. A separate include for the C compilation should include declarations of all the functions above.
EDIT: The caveats and comments below are important; to answer the question, "Yes it is possible to call C++ from C", and this is one approach. It's not a complete approach as there isn't really a mechanistic way to do it, but it's a start. Also, don't forget to create another call-through for delete, etc, etc.
Q: Can I access my C code from C++ or vice versa?
A: Yes.
1) The main thing is to use extern "C" { ...} in all your headers to denote C-only functions and data, like this:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
/* Header file foo.h */
#ifdef __cplusplus /* If this is a C++ compiler, use C linkage */
extern "C" {
#endif
/* These functions get C linkage */
void foo();
struct bar { /* ... */ };
#ifdef __cplusplus /* If this is a C++ compiler, end C linkage */
}
#endif
2) The usual scenario is a C++ main program that calls a mix of C and C++ functions and structs. The structs and functions are all declared in headers, and all have "#ifdef __cplusplus/extern C".
3) Here is a good FAQ on mixing C and C++:
http://www.parashift.com/c++-faq/mixing-c-and-cpp.html
Unless strictly required, this is only for dyied-in-the-wool masochists. Doing it will require extreme care on both sides, and could well work today and explode spectacularly with the next compiler update. C++ requires a lot of runtime help, and getting that to work reliably from C isn't normally supported. You can call into C from C++, that is officially supported (and part of the standard, extern "C" and such).
Probably the best bet is to write your C in the subset handled by C and C++ (a starting point on the subtle differences is this) and compile with the C++ compiler. Or get over it and decide what language you like most.
yes, you need to specify it as
extern "C"
this way it will make the function to have "C" linkage, then C code can call your function just as if it was in C. This function name will not be mangled then because C doesn't support overloading.
here let me cite #Faisal Vali:
extern "C" is a linkage-specification
Every compiler is required to provide "C" linkage
a linkage specification shall occur only in namespace scope
all function types, function names and variable names have a language linkage
two function types with distinct language linkages are distinct types even if otherwise identical
linkage specs nest, inner one determines the final linkage
extern "C" is ignored for class members
at most one function with a particular name can have "C" linkage (regardless of namespace)
extern "C" forces a function to have external linkage (cannot make it static)
Linkage from C++ to objects defined in other languages and to objects defined in C++ from other languages is implementation-defined and language-dependent. Only where the object layout strategies of two language implementations are similar enough can such linkage be achieved
see Faisal Vali answer here
I know how to use extern "C" but what are the conditions when you have to use it?
extern "C" tells the C++ compiler not to perform any name-mangling on
the code within the braces. This allows you to call C functions from
within C++.
For example:
#include <string.h>
int main()
{
char s[] = "Hello";
char d[6];
strcpy_s(d, s);
}
While this compiles fine on VC++. But sometimes this is written as:
extern "C" {
#include <string.h>
}
I don't see the point. Can you give a real example where extern "C" is necessary?
You use extern "C" to prevent name mangling inside header files and your C++ object files for libraries or objects that have already been compiled without mangling.
For example, say you have a widget library which was compiled with a C compiler so that its published interface is non-mangled.
If you include the header file as is into your code, it will assume the names are mangled and those mangled versions are what you'll tell the linker to look for.
However, since you'll be asking for something like function#intarray_float_charptr and the widget library will have only published function, you're going to run into problems.
However, if you include it with:
extern "C" {
#include "widget.h"
}
your compiler will know that it should try to use function, the non-mangled version.
That's why, in header files for C stuff meant to be included in C _or C++ programs, you'll see things like:
#ifdef __cplusplus
extern "C" {
#endif
// Everything here works for both C and C++ compilers.
#ifdef __cplusplus
}
#endif
If you use a C compiler to include this, the #ifdef lines will cause the extern "C" stuff to disappear. For a C++ compiler (where __cplusplus is defined), everything will be non-mangled.
One very common use of extern "C" when you are exporting a function from a library. If you don't disable C++ name mangling you can otherwise make it very hard for clients of your library to name your function. And likewise, when going in the other direction, when you are importing a function that has been exported with C linkage.
Here is a concrete example of where things break and need extern "C" to get fixed.
module.h:
int f(int arg);
module.c:
int f(int arg) {
return arg + 1;
}
main.cpp:
#include "module.h"
int main() {
f(42);
}
Since I am mixing C and C++, this won't link (of the two object files, only one will know f under its C++ mangled name).
Perhaps the cleanest way to fix this is by making the header file compatible with both C and C++:
module.h:
#ifdef __cplusplus
extern "C" {
#endif
int f(int arg);
#ifdef __cplusplus
}
#endif
When you link with libraries that are written in C extern tells the compiler not to decorate the names so that the linker can find the functions. In C++ function names et al have information for the linker e.g. argument types and sizes contained in the name.
If you are producing a binary library A that exposes a function that you would like to call from binary B.
Imagine A is A.dll and B is B.exe and you are on a Windows system.
C++ does not describe a binary layout such that B knows how to call A. Typically this problem is worked around by using the same compiler to produce A and B. If you want a more generic solution you use the extern keyword. This exposes the function in a C manner. C does describe a binary format so that different binaries from different compilers can talk to each other.
See:
http://en.wikipedia.org/wiki/Application_binary_interface
http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B
If, inside your C++ code, you #include a header for an external library (coded in C) and if the functions there are not declared extern "C" they wont work (you'll get undefined reference at link time).
But these days, people coding C libraries and providing header files for you tend to know that, and often put the extern "C" in their header file (suitably protected with #ifdef __cplusplus)
Perhaps a better way to understand is to use (assuming you have a Linux system) the nm utility to show you the (unmangled) names used in a library or an executable.