c++ - __cxa_finalize 和 __attribute__

标签 c++ linux

据我所知,一个程序(在 Linux 中用 C++ 编写)在退出 main 函数时调用 __cxa_finalize。我创建了一个共享库并在主函数中使用了这个库。我想在主程序加载/卸载这个库时采取一些行动。我发现函数 __attribute__ 在创建共享库时可以用于该目的(我猜这个函数应该在共享库代码中实现)

我添加了如下内容:

void __attribute__ ((constructor)) my_load(void);

void __attribute__ ((destructor)) my_unload(void);

我在以下链接中实现了函数 my_load 和 my_unload: http://tdistler.com/2007/10/05/implementing-dllmain-in-a-linux-shared-library

问题是这些函数在退出主函数时究竟是按什么顺序处理的? my_unload() 函数还是 __cxa_finalize

最佳答案

gcc documentation for constuctor/destructor attribute说:

You may provide an optional integer priority to control the order in which constructor and destructor functions are run. A constructor with a smaller priority number runs before a constructor with a larger priority number; the opposite relationship holds for destructors. So, if you have a constructor that allocates a resource and a destructor that deallocates the same resource, both functions typically have the same priority. The priorities for constructor and destructor functions are the same as those specified for namespace-scope C++ objects.

在我使用 gcc-4.7.0 的测试中,构造函数在 C++ 全局对象构造函数之前运行,而析构函数在 C++ 全局对象析构函数之后运行,当两者都在同一个翻译单元中时,无论声明/定义的顺序如何。

更新:Ian Lance Taylor 报告未指定具有构造函数属性和 C++ 全局构造函数的函数的执行顺序。参见 http://gcc.gnu.org/ml/gcc-help/2012-05/msg00118.html

在 C++ 中,您可以使用 Schwarz Counter 确保某些对象在任何其他全局对象之前被初始化,并在多个翻译单元之后被销毁。成语。

关于c++ - __cxa_finalize 和 __attribute__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10634767/

相关文章:

c++ - 骨骼动画

linux - 你如何构建 gstreamer 的 gst-launch 管道?

linux - 运行python时如何使shell脚本阻塞?

linux - DOCKER_OPTS 在系统重启后重置

linux - perf 中预定义事件的原始编码

c++ - 最烦人的解析

c++ - C++ 中的哈希函数 SHA1

c++ - 实现质数计数器

c++ - 重用的boost ptree是否需要清除?

linux - 超过 4 GB 的 Zip 文件损坏 - 没有警告或错误 - 我是否丢失了数据?