Chinaunix首页 | 论坛 | 博客
  • 博客访问: 450906
  • 博文数量: 80
  • 博客积分: 2301
  • 博客等级: 大尉
  • 技术积分: 884
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-16 20:07
个人简介

I\'m interested in mathematics and Daoism. Welcome to talk about these subjects with me.

文章分类

全部博文(80)

文章存档

2017年(2)

2016年(16)

2015年(4)

2014年(6)

2013年(22)

2012年(2)

2011年(1)

2010年(4)

2009年(20)

2008年(2)

2007年(1)

我的朋友

分类: C/C++

2008-07-27 10:04:35

gcc 对c程序的函数做了很多扩展。一个很有趣的扩展,给一个c程序增加构造函数。如下的函数原型声明了一个函数为程序的构造函数:

void func() __attribute__((constructor));
这种构造函数有点类似于c++的构造函数,它是程序自动调用的,并且先于main函数儿调用。现在有这样一个问题,如果一个程序在多个文件中有多个构造函数,它们的调用顺序是什么样的呢?下面的测试程序回答了这个问题:

//main.c file
#include
#include
#include
#include"other.h"
 
void func1() __attribute__((constructor));
void func2() __attribute__( (constructor) );
 
void func1()
{
        printf("%s\n",__func__);
}
 
void func2()
{
        printf("%s\n",__func__);
}
 
 
int main()
{
        printf("main\n");
        return 0;
}
//main.c fiule ends

//other.h file
#ifndef OTHER_H
#define OTHER_H
void func_in_other_file() __attribute__((constructor));
#endif 
//other.h file ends


//other.c file
#include "other.h"
 
void func_in_other_file()
{
        printf("%s\n",__func__);
}
//other.c file ends

使用cc -o t ./main.c ./other.c命令编译,执行./t,输出如下:
func_in_other_file
func2
func1
main

使用cc -o t ./other.c ./main.c 命令编译,执行./t,输出如下:
func2
func1
func_in_other_file
main

可见:
1)构造函数先于main函数而执行
2)不同构造函数如果在同一个文件中,则先出现的函数后执行
3)对于不同文件中的构造函数,编译命令中后出现的.c文件的构造函数先执行









阅读(1845) | 评论(0) | 转发(0) |
0

上一篇:strtok_r函数研究

下一篇:/GF编译选项

给主人留下些什么吧!~~