This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
throwing C++ exceptions across C frames
- From: Ben Liblit <liblit at eecs dot berkeley dot edu>
- To: gcc at gcc dot gnu dot org
- Date: Mon, 30 Dec 2002 20:50:30 -0800
- Subject: throwing C++ exceptions across C frames
I am working with a mixed C/C++ code base. Occasionally, the C++ code
may want to throw an exception. If there are only C++ function calls on
the stack between the "throw" and the "catch", then the exception is
caught properly.
However, if...
- the C++ "catch" code calls some C function
- this C function then calls back into C++ code
- this C++ code now throws an exception
...then the exception is not caught and the program aborts as though it
had run into an uncaught exception. It appears as though stack
unwinding and exception dispatch will not cross over a C stack frame.
Is there any possible way to make this work? I realize that lobbing
exceptions over the top of unsuspecting C code is questionable anyway,
but this is a large existing code base and I don't have the option of,
say, reworking everything in C++.
I am using gcc-3.2, g++-3.2, libstdc++-3.2, and glibc-2.2.93 on a Red
Hat Linux 8.0 box. Example code follows.
#include <cstdio>
#include "c.h"
#include "cxx.h"
void toss()
{
throw 7;
}
int main()
{
try
{
transfer();
}
catch (...)
{
puts("caught exception");
}
return 0;
}
#include <stdio.h>
#include "c.h"
#include "cxx.h"
void transfer()
{
puts("transfer: before call");
toss();
puts("transfer: after call (!!)");
}
CC = gcc
CFLAGS = -g -W -Wall -Werror
CXX = g++
CXXFLAGS = -g -W -Wall -Werror
main: cxx.o c.o
$(CXX) $(CXXFLAGS) $^ -o $@
cxx.o: cxx.cc
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $<
c.o: c.c
$(CC) $(CPPFLAGS) $(CFLAGS) -c $<
clean:
rm -f main cxx.o c.o