g++ can't override exit function

我是研究僧i 提交于 2020-01-06 07:10:35

问题


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


回答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:

  • http://www.cplusplus.com/reference/cstdlib/atexit
  • https://www.gnu.org/software/libc/manual/html_node/Cleanups-on-Exit.html


来源:https://stackoverflow.com/questions/53531550/g-cant-override-exit-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!