究竟如何__attribute __((构造函数))工作? [英] How exactly does __attribute__((constructor)) work?

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

问题描述

这似乎pretty清楚,它应该设置的东西了。


  1. 在当前正是它运行?

  2. 为什么有两个括号?

  3. __ __属性函数?宏?语法?

  4. 请问用C这项工作? C ++?

  5. 是否与工作需要的功能是静态的?

  6. 什么时候 __ __属性((析构函数))运行?

<一个href=\"http://stackoverflow.com/questions/2046426/initialising-a-static-variable-in-objective-c-category/2046997#2046997\">Example在目标C :

  __ __属性((构造函数))
静态无效initialize_navigationBarImages(){
  navigationBarImages = [[的NSMutableDictionary的alloc]初始化];
}__attribute __((析构函数))
静态无效destroy_navigationBarImages(){
  [navigationBarImages发布]
}


解决方案

  1. 它时加载的共享库运行,通常在程序启动。

  2. 这是所有GCC属性如何; presumably从函数调用区别开来。

  3. 针对GCC-语法。


  4. 无。

  5. 的析构当共享库卸载运行,通常在程序退出。

所以,一路构造函数和析构函数的工作是共享对象文件包含特殊路段包含分别标有构造和析构的属性,该函数的引用(ELF上和.ctors .dtors)。当库加载/卸载的动态装载程序(ld.so或诸如此类)检查是否存在这样的部分,并且如果是的话,呼叫参考在其中的功能。

试想想起来了,有可能是正常的静态连接一些类似的魔法,使同一code是启动/关机运行,如果不考虑用户选择静态或动态链接。

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

  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?

Example in Objective C:

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

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

解决方案

  1. It's run when a shared library is loaded, typically during program startup.
  2. That's how all GCC attributes are; presumably to distinguish them from function calls.
  3. GCC-specific syntax.
  4. Yes.
  5. No.
  6. The destructor is run when the shared library is unloaded, typically at program exit.

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 __((构造函数))工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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