关于GCC的__attribute__(constructor)

来源:互联网 发布:女留学生遇害 知乎 编辑:程序博客网 时间:2024/05/20 04:32

转自:http://blog.chinaunix.net/uid-24512513-id-3195102.html

今天写一个动态库,需要让动态库有一个类似于windows的DLLMain函数一样功能的函数,可惜发现Linux没有这样的功能,于是查阅了大量的资料,最后发现GCC的__attribute__属性设置可以将函数设置成类似于这样功能的函数:

  1. __attribute__((constructor)) // 在main函数被调用之前调用
  2. __attribute__((destructor)) // 在main函数被调用之后调
一个简单的例子如下:

点击(此处)折叠或打开

  1. #include<stdio.h> 
  2. __attribute__((constructor)) void before_main() { 
  3.    printf("before main\n"); 
  4. } 

  5. __attribute__((destructor)) void after_main() { 
  6.    printf("after main\n"); 
  7. } 
  8.   
  9. int main(int argc, char **argv) { 
  10.    printf("in main\n"); 
  11.    return 0; 
  12. }
这个例子的输出结果将会是:
  1. before main
  2. in main
  3. after main
原创粉丝点击