C 语言中的constructor与destructor

来源:互联网 发布:linux查看cpu核数命令 编辑:程序博客网 时间:2024/06/11 21:11
 最近在看代码的时候碰到一个问题,这项目中有一个全局变量,里面有许多系统用的属性。但是一直找不到它在哪里被赋值。后来跟了代码才发现在系统开始之前已经有一个constructor将这个东西初始化好。 
   GCC可以给函数若干属性,其中construction就是其中一个。具体有哪些属性,可以看GCC的文档。http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 
   在上面文档中有对于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 <stdio.h>  
  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;  
  20. }  

   
  运行的结果为: 

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