Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1120148
  • 博文数量: 177
  • 博客积分: 761
  • 博客等级: 上士
  • 技术积分: 1518
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-04 22:37
文章分类

全部博文(177)

文章存档

2017年(1)

2016年(3)

2015年(33)

2014年(48)

2013年(60)

2012年(32)

分类: LINUX

2013-01-21 11:22:00

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



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