加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – __cxa_finalize和__attribute__

发布时间:2020-12-16 07:30:41 所属栏目:百科 来源:网络整理
导读:据我所知,一个程序(在 Linux中用C编写)在退出main函数时调用__cxa_finalize.我创建了一个共享库,并在main函数中使用了这个库.我想在主程序加载/卸载此库时采取一些操作.我发现函数__attribute__可以在创建共享库时用于此目的(这个函数应该在我猜的共享库代码
据我所知,一个程序(在 Linux中用C编写)在退出main函数时调用__cxa_finalize.我创建了一个共享库,并在main函数中使用了这个库.我想在主程序加载/卸载此库时采取一些操作.我发现函数__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惯用法在多个翻译单元之后被销毁.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读