0

I have a c++ program where I want to compile out std::exit and use my own, i.e. via:

-Dexit=myExit

However, I run into this issue:

In file included from /usr/include/c++/7/ext/string_conversions.h:41:0,
                 from /usr/include/c++/7/bits/basic_string.h:6352,
                 from /usr/include/c++/7/string:52,
                 from /usr/include/c++/7/bits/locale_classes.h:40,
                 from /usr/include/c++/7/bits/ios_base.h:41,
                 from /usr/include/c++/7/ios:42,
                 from /usr/include/c++/7/istream:38,
                 from /usr/include/c++/7/sstream:38,
                 from tests/helpers.h:4,
                 from tests/helpers.cpp:1:
/usr/include/c++/7/cstdlib:146:11: error: ‘::exit’ has not been declared
   using ::exit;

I'm running it on virtualBox: Ubuntu 18.04 / 18.10 / Debian 10

jajabarr
  • 551
  • 2
  • 5
  • 19
  • Who told you that this is something valid you can do in C++? – Brian Bi Nov 29 '18 at 03:54
  • @Brian https://stackoverflow.com/questions/14199689/how-can-i-handle-exit-calls-in-3rd-party-library-code I have also had it working in macOs but unfortunately I really need it in linux – jajabarr Nov 29 '18 at 03:59
  • The best way to do this is to just change the source code to call `myExit` directly. – Cornstalks Nov 29 '18 at 04:04
  • @Cornstalks that is not an option in my case, I must be able to do it at compile time – jajabarr Nov 29 '18 at 04:20

1 Answers1

1

Instead of overriding exit on your own, which is non standard and risky, you could register your own functions to be executed at program exit using atexit.

atexit takes a function pointer parameter, (void (*func)(void)), and registers that function to be executed by exit (for reference, see glibc exit.c source code).

With this approach, you could register multiple functions to be executed at exit, plus, atexit behaviour is well defined in the C++ standard.

For examples and documentation, see:

valiano
  • 16,433
  • 7
  • 64
  • 79
  • Unfortunately rather than 'extra' code being ran at exit, I would prefer the function exiting to instead throw an exception that can be caught. Raising an exception from an atexit regsiter still causes the program to terminate. – jajabarr Nov 29 '18 at 13:41
  • @jajabarr could you please explain, where the exception will be caught? Are you running with some special environment? I don't think the C++ runtime allows for exceptions at exit. – valiano Nov 29 '18 at 17:45