GCC __attribute__((constructor)|(destructor))
2014-01-20 22:57
330 查看
在阅读TGTD的代码时发现了一个非常诡异的问题,声明了一个空的全局数组,在使用的时候却发现数组非空,在main()入口时数组已经非空.数组时在什么地方被赋值了呢?最后发现__attribute__这个东东在起作用,类似于全局变量类的构造函数在main()前被调用.
根据上面的代码以及输出结果,我们可以猜到__attribute__((constructor))表示这段代码将在main函数前调用,就像在C++里面的全局变量类的构造一样.说到C++里面的全局类对象的构造,我们不禁要问全局类对象的构造跟__attribute__((constructor))以及destructor谁在前谁在后呢?
可以看到全局类的构造过程发生在before_main()函数前面,而析构也发生在after_main()前面.
__attribute__((constructor)) __attribute__((destructor)) #include<stdio.h> __attribute__((constructor)) void before_main() { printf("before main\n"); } __attribute__((destructor)) void after_main() { printf("after main\n"); } int main() { printf("in main\n"); return 0; } $ gcc test.c -o test $ ./test before main in main after main
根据上面的代码以及输出结果,我们可以猜到__attribute__((constructor))表示这段代码将在main函数前调用,就像在C++里面的全局变量类的构造一样.说到C++里面的全局类对象的构造,我们不禁要问全局类对象的构造跟__attribute__((constructor))以及destructor谁在前谁在后呢?
#include<iostream> using namespace std; __attribute__((constructor)) void before_main() { cout<<"Before Main"<<endl; } __attribute__((destructor)) void after_main() { cout<<"After Main"<<endl; } class AAA{ public: AAA(){ cout<<"AAA construct"<<endl; } ~AAA(){ cout<<"AAA destructor" <<endl; } }; AAA A; int main() { cout<<"in main"<<endl; return 0; } $ make test2 $ ./test2 AAA construct Before Main in main AAA destructor After Main
可以看到全局类的构造过程发生在before_main()函数前面,而析构也发生在after_main()前面.
相关文章推荐
- asp获取文件名和扩展名的函数代码
- 豪迪qq群发器2014破解版去除尾巴注册机2014最新qq群发
- Codeforces 379D - New Year Letter
- Stanford-CV华人教授李飞飞写给她学生的一封信,如何做好研究以及写好PAPER,受益匪浅
- SqlServer 杂记 不断补充中
- win7设置定时关机
- 3718. 批改作业 不难 开了个二维数组
- 【rails3教材】博客构建过程2
- bash 定时任务
- ProGuard的Maven插件配置
- MongoDB
- MON166 User's Guide
- 在Delphi下基于MapWinGIS添加和删除图层标注的方法
- JAVA/JSP中引入JFreeChart进行统计图显示
- 莱鸟学apache DBCP(一)之BasicDataSourceFactory
- VS2010+Selenium测试脚本设计
- 什么是STL
- make3d: learning 3d scene structure from a single still image完全解读
- Eclipse中汉字字符编码问题
- Google 多源码管理工具 gclient .