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()之前运行..