Chinaunix首页 | 论坛 | 博客
  • 博客访问: 622419
  • 博文数量: 79
  • 博客积分: 848
  • 博客等级: 军士长
  • 技术积分: 1800
  • 用 户 组: 普通用户
  • 注册时间: 2012-06-26 19:30
文章分类

全部博文(79)

文章存档

2015年(4)

2013年(39)

2012年(36)

分类: C/C++

2013-04-18 09:47:06

转载:http://peng-wp.iteye.com/blog/1483901
最近在看代码的时候碰到一个问题,这项目中有一个全局变量,里面有许多系统用的属性。但是一直找不到它在哪里被赋值。后来跟了代码才发现在系统开始之前已经有一个constructor将这个东西初始化好。
   GCC可以给函数若干属性,其中construction就是其中一个。具体有哪些属性,可以看GCC的文档。
   在上面文档中有对于constructor与destructor的描述:
引用

constructor
destructor
constructor (priority)
destructor (priority)
The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.
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 (see C++ Attributes).

These attributes are not currently implemented for Objective-C.


   大致意思就是,可以给一个函数赋予constructor或destructor,其中constructor在main开始运行之前被调 用,destructor在main函数结束后被调用。如果有多个constructor或destructor,可以给每个constructor或 destructor赋予优先级,对于constructor,优先级数值越小,运行越早。destructor则相反。
   下面是一个例子:
C代码  收藏代码
  1. #include   
  2.   
  3. __attribute__((constructor(101))) void foo()  
  4. {  
  5.     printf("in constructor of foo\n");  
  6. }  
  7. __attribute__((constructor(102))) void foo1()  
  8. {  
  9.     printf("in constructor of foo1\n");  
  10. }  
  11. __attribute__((destructor)) void bar()  
  12. {  
  13.     printf("in constructor of bar\n");  
  14. }  
  15.   
  16. int main()  
  17. {  
  18.         printf("in main\n");  
  19.         return 0;  

  
  运行的结果为:

in constructor of foo
in constructor of foo1
in main
in constructor of bar


阅读(1967) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~