#include <stdio.h>
typedef int (*init_fn_t)(void);
#define SECTION(level) __attribute__((used,section(".init."level)))
int xxx_init_start(void)
{
return 0;
}
const init_fn_t init_fn_xxx_init_start SECTION("0") = xxx_init_start;
int main()
{
/* Write C code in this online editor and run it. */
printf("Hello, World! \n");
return 0;
}
附一些参考文档:
1. 讲的很好,我就是看这个学会的:
__attribute__((used)) __attribute__((section(x)))_EmbededCoder的博客-优快云博客
2. 概念性介绍写的比较全:
C语言中的__attribute__宏定义之section属性_Ythlee的博客-优快云博客_c语言section
3. 官方网站:
Using the GNU Compiler Collection (GCC)
4. 可以稍微参考:
C语言中的__attribute__宏定义之section属性_Ythlee的博客-优快云博客_c语言section
//从上面链接拷贝来的一些概念性介绍
一、介绍
GNU C 的一大特色就是__attribute__ 机制
attribute 可以设置函数属性(Function Attribute )、变量属性(Variable Attribute )和类型属性(Type Attribute )。
attribute 书写特征是:attribute 前后都有两个下划线,并切后面会紧跟一对原括弧,括弧里面是相应的__attribute__ 参数。
attribute 语法格式为:attribute ((attribute-list))
关键字__attribute__ 也可以对结构体(struct )或共用体(union )进行属性设置。大致有六个参数值可以被设定,即:aligned, packed, transparent_union, unused, deprecated 和 may_alias 。
在使用__attribute__ 参数时,你也可以在参数的前后都加上“__” (两个下划线),例如,使用__aligned__而不是aligned ,这样,你就可以在相应的头文件里使用它而不用关心头文件里是否有重名的宏定义。
__attribute__主要用于改变所声明或定义的函数或数据的特性,它有很多子项,用于改变作用对象的特性。比如对函数,noline将禁止进行内联扩展、noreturn表示没有返回值、pure表明函数除返回值外,不会通过其它(如全局变量、指针)对函数外部产生任何影响。但这里我们比较感兴趣的是对代码段起作用子项section。
__attribute__的section子项的使用格式为:
__attribute__((section("section_name")))
其作用是将作用的函数或数据放入指定名为"section_name"输入段。
二、使用:section
提到section,就得说RO RI ZI了,在ARM编译器编译之后,代码被划分为不同的段,RO
Section(ReadOnly)中存放代码段和常量,RW Section(ReadWrite)中存放可读写静态变量和全局变量,ZI Section(ZeroInit)是存放在RW段中初始化为0的变量
attribute((section(“section_name”))),其作用是将作用的函数或数据放入指定名为"section_name"对应的段中。
编译时为变量指定段名
附带:
在宏定义中两个##号相当于无缝连接的意思,比如
#define DEF_INT(a,b) int a##b = 0
DEF_INT(a,b);
//展开结果就是
int ab = 0;