g ++无法覆盖退出功能 [英] g++ can't override exit function

查看:82
本文介绍了g ++无法覆盖退出功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++程序,我想在其中编译出std :: exit并使用自己的程序,即通过以下方式进行操作:

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;

我正在virtualBox上运行它:Ubuntu 18.04 / 18.10 / Debian 10

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

推荐答案

您可以注册,而不是自行覆盖退出,因为这是非标准且有风险的您自己的函数,可以使用 atexit 在程序退出时执行。

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 采用函数指针参数,(void(* func)(void) ),并注册要由 exit 执行的功能(有关参考,请参见 glibc exit.c源代码)。

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).

采用这种方法,您可以注册要在退出时执行的多个函数,此外, atexit 行为在C ++标准中已得到很好的定义。

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

这篇关于g ++无法覆盖退出功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆