__attribute__(()) 不是标准C里面的东西,而是GCC的扩展特殊符号。 不同编译器都有些自带的扩展特殊符号。 这里记录gcc的attribute的两个作用
1. 用于memory alignment (这个作用类似于IAR #pragma pack(push, n) & #pragma pack(pop) )
对于32位系统,默认情况下,结构体变量在内存中是按照字对齐的。例如下面的例子
typedef struct{
uint8_t a;
uint16_t b;
uint32_t c;
}test1;
如果用sizeof运算的话,这个结构体的size是8字节,因为系统自动补齐了1个字节,进而达到字对齐
typedef struct{
uint8_t a;
uint16_t b;
uint32_t c;
}__attribute__((aligned(1),packed)) test2;
如果用sizeof运算这个test2, 那么这个结构体就是7个字节。
2. 用于将变量固定到一个地址上去
2.1 在源文件上定义变量 int test1 __attribute__((section(".mySection"))) = 0x9ABCDEF0;
2.2 修改.ld文件(链接文件)
SECTIONS
{
.mySegment 0x12345678:{KEEP(*(.mySection))}
}
这样就把test1固定到12345678内存地址上。
当然更好的办法应该是这样的
int *test = (int *)(0x12345678);
*test = 0x9ABCDEF0;
参考资料:
https://stackoverflow.com/questions/2554229/memory-alignment-within-gcc-structs