|
|
When an application has a mixture of C++ and C code, the question arises as to how exception handling works.
The most typical case involves C++ code that sets up a try block and then calls a C function, which in turn calls a C++ function that may throw an exception. A simple example:
file1.F (C++):
extern "C" void bar(int);void foo() { try { bar(7); } catch (int i) { // do something } }
file2.c (C):
extern void gok(int);void bar(int k) { gok(k*k); }
file3.C (C++):
extern "C" void gok(int i) { throw i; }
This will work correctly in the C++ and C compilers.
There can be various intervening layers of C++ and C functions between
the try block and the throw. However, there is one very important
restriction:
All C functions that may have an exception thrown through
them MUST be compiled with the cc -Kframe option.
This is because the C++ runtime system needs to be able to unwind any stacks from the point of the throw to the point of the handler, and if those stacks are from C functions, the full frame pointer model (which is what -Kframe specifies) is the only one that is self-descriptive enough for the runtime system to understand.
So in the above example, file2.c must be compiled with -Kframe. Optimization may still be used, i.e., cc -O -Kframe is allowed.
Note that this constitutes a significant restriction regarding Gemini or third-party libraries that employ "callback" functions. Examples include qsort(3C) and bsearch(3C) from the Standard C library, and many functions from the X Window System. In general these libraries will have been compiled with the -Kno_frame option (for performance reasons). As a consequence, if C++ functions are being used for those callbacks, such functions cannot exit via an exception. (They can however use exceptions to throw and catch exceptions internally, and then translate caught exceptions into some meaningful error code to the library interface.)
There is no support for forms of mixed-language exception handling in which C functions are able to "throw" or "catch" exceptions imported from C++ code.