关于GCC的__attribute__(constructor)

1020阅读 0评论2013-01-21 lubing521
分类:LINUX

今天写一个动态库,需要让动态库有一个类似于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



上一篇:《深入Linux设备驱动程序机制》学习心得---字符设备驱动原理图解
下一篇:一道小学数学题[状元蹄]