克++不能覆盖出口功能(g++ can't override exit function)

2019-10-30 04:02发布

我有一个C ++程序,我想编出来的std ::退出,用我自己的,即通过:

-Dexit=myExit

但是,我碰到这个问题:

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 / 10的Debian

Answer 1:

相反,覆盖的exit你自己,这是非标准和有风险的,你可以注册使用在程序退出执行自己的函数atexit

atexit取一个函数指针参数, (void (*func)(void))和其功能是由执行寄存器exit (作为参考,见glibc的exit.c中的源代码 )。

通过这种方法,你可以注册在出口处被执行多种功能,再加上, atexit的行为是在C ++标准明确界定。

对于实例和文档,请参阅:

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


文章来源: g++ can't override exit function
标签: c++ g++ clang