Re: exit() from within C++ program
On May 10, 3:26 pm, chris <craph...@indiana.edu> wrote:
Without changing each instance of exit to something else, I would like to
change things so that my program will at least terminate normally,
maybe with a concilliatory message.
You could do that by registering a handler with atexit(). In fact
this is possible in C as well.
Of course a better solution is to design your C API so that
it returns error codes instead of calling exit().
NB. Here is a brutal hack I thought of that might work.
In a common header file for your C code (that is NOT
included by any C++ code), write:
#define exit(arg) hack_exit(arg)
void hack_exit(int x);
Then in one of the C++ modules write:
extern "C" void hack_exit(int x) {
throw std::runtime_error("C code tried to exit");
}
Then any attempted exit by the C code would show up as an
exception that can be handled by the C++ part. Which could
even just be wrapping main:
int main2() { /* the main program */ }
int main() {
try { main2(); }
catch(std::execption &e) { std::cout << "Aborting: " << e.what() <<
std::endl; }
}