gcc 函数属性 __attribute__ ((constructor))使用

gcc 函数属性 attribute ((constructor))使用


  • 预备知识

在程序中有时希望在main()函数之前运行一段函数,比如初始化函数,注册函数等,会使用到gcc 的函数属性 attribute ((constructor)),
当函数被设置constructor属性,会在main()函数之前运行,完成预期的行为。设置constructor属性的申明方式如下:

static int xxx_init(void) __attribute__ ((constructor));
static int register_init(void) __attribute__ ((constructor));

下面举一个 attribute ((constructor)) 属性使用的demo,可在此处获取demo 。在demo中演示了gpio_init(void) 和 key_init(void)
如何设置attribute ((constructor)) 属性,同时演示了添加key.c文件的不需要修改main.c的方法,此方法能减少对main.c的修改,也体现
了软件设计–高内聚低耦合的思想。程序运行的结果如下:

registered gpio_init fun complete..
start main fun..
iterate list ..
handle three command..
handle two command..
handle one command..
iterate list ..
handle three command..
handle two command..

添加key.c后运行结果如下:

registered gpio_init fun complete..
registered key_init fun complete..
start main fun..
iterate list ..
key two..
key one..
handle three command..
handle two command..
handle one command..
iterate list ..
key two..
key one..

从运行结果看出来,gpio_init()和key_init()函数在main()之前运行..


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值