__attribute__((constructor)) 究竟是如何工作的? [英] How exactly does __attribute__((constructor)) work?

查看:29
本文介绍了__attribute__((constructor)) 究竟是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显,它应该进行设置.

It seems pretty clear that it is supposed to set things up.

  1. 它到底什么时候运行?
  2. 为什么有两个括号?
  3. __attribute__ 是一个函数吗?一个宏?语法?
  4. 这在 C 中有效吗?C++?
  5. 它所使用的函数是否需要是静态的?
  6. __attribute__((destructor)) 什么时候运行?
  1. When exactly does it run?
  2. Why are there two parentheses?
  3. Is __attribute__ a function? A macro? Syntax?
  4. Does this work in C? C++?
  5. Does the function it works with need to be static?
  6. When does __attribute__((destructor)) run?

Objective-C 中的示例:

__attribute__((constructor))
static void initialize_navigationBarImages() {
  navigationBarImages = [[NSMutableDictionary alloc] init];
}

__attribute__((destructor))
static void destroy_navigationBarImages() {
  [navigationBarImages release];
}

推荐答案

  1. 它在加载共享库时运行,通常是在程序启动期间.
  2. 所有 GCC 属性都是这样;大概是为了将它们与函数调用区分开来.
  3. 特定于 GCC 的语法.
  4. 是的,这适用于 C 和 C++.
  5. 不,该函数不需要是静态的.
  6. 析构函数在共享库卸载时运行,通常是在程序退出时.

因此,构造函数和析构函数的工作方式是共享对象文件包含特殊部分(ELF 上的 .ctors 和 .dtors),其中包含对分别标有构造函数和析构函数属性的函数的引用.当库被加载/卸载时,动态加载程序(ld.so 或 somesuch)会检查这些部分是否存在,如果存在,则调用其中引用的函数.

So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.

想想看,普通的静态链接器中可能有一些类似的魔法,因此无论用户选择静态链接还是动态链接,都会在启动/关闭时运行相同的代码.

Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.

这篇关于__attribute__((constructor)) 究竟是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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