I've got C++ functions that I want to declare using extern "C"
even though they are only called in C++ code. Yes, I know this is strange but it's something I would like to do for consistency since we have mixed C and C++ declarations. I just want to make sure that declaring a C++ function as extern "C"
won't affect the behavior of throwing.
It would look something like this:
extern "C" void foo() {throw exception;} int bar() { try { foo(); } catch (exception e) { return 1; } }
By declaring a function with extern "C" , it changes the linkage requirements so that the C++ compiler does not add the extra mangling information to the symbol. This pattern relies on the presence of the __cplusplus definition when using the C++ compiler. If you are using the C compiler, extern "C" is not used.
extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block. In a template declaration, extern specifies that the template has already been instantiated elsewhere.
the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit.
The extern “C” keyword is used to make a function name in C++ have the C linkage. In this case the compiler does not mangle the function. Let us see what is the mangling in C++ first, then we can discuss about the extern “C” keyword. In C++ we can use the function overloading feature.
"Can C++ functions marked as Extern “C” throw?"
Yes, in the sense that neither the language nor the compiler will prevent you from doing so.
No, in the sense that if you throw, it would be an undefined behaviour, as the C++ exception crosses language boundaries.
In practice: do not do it. Catch the exception and translate it into an error code, or a means the other language can understand.
So the bottomline is: do NOT throw exception from functions marked as extern "C"
.
For GCC the answer seems inconclusive.
The MSVC documentation, however is relatively clear on the subject:
/EHa
and /EHs
... tells the compiler to assume that functions declared as extern "C" may throw an exception. /EHsc
... tells the compiler to assume that functions declared as extern "C" never throw a C++ exception So for Visual-C++ it depends on the compiler options whether you get defined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With