上篇文章:【ARM 嵌入式 编译系列 11.1 – GCC attribute((aligned(x)))详细介绍】
上篇文章:【ARM 嵌入式 编译系列 11.3 – GCC attribute packed noreturn constructor 介绍】
attribute((aligned(x)))详细介绍
__attribute__((aligned(x)))
是 GCC 编译器的一个特性,它可以用于变量或类型,用来指定它们在内存中的对齐方式。
默认情况下,编译器会对数据按照特定的对齐原则进行对齐,以提高处理器对数据的访问效率。例如,在大多数系统中,一个 int
类型的变量默认会按照 4
字节对齐。
以下是一个示例:
#include <stdio.h>
struct aligned_struct {
int a;
char b;
int c;
};
int main(void)
{
struct aligned_struct s;
printf("Size of aligned_struct: %lu\n", sizeof(struct aligned_struct));
printf("Address of s: %p\n", &s);
return 0;
}
[09:25:51]sam@sam (*^~^*) ~/workbase/test> gcc -g test.c -o test
[09:25:53]sam@sam (*^~^*) ~/workbase/test> ./test
Size of aligned_struct: 12
Address of s: 0x7ffe9932c8ac
使用 __attribute__((aligned(x)))
可以指定变量或类型的对齐方式,其中 x
是对齐的字节数,必须是 2
的幂次。编译器将保证变量或类型的地址是指定字节数的倍数。
#include <stdio.h>
struct aligned_struct {
int a;
char b;
int c;
}__attribute__((aligned(16)));
int main(void)
{
struct aligned_struct s;
printf("Size of aligned_struct: %lu\n", sizeof(struct aligned_struct));
printf("Address of s: %p\n", &s);
return 0;
}
在这个示例中,aligned_struct
结构体使用 __attribute__((aligned(16)))
指定了 16
字节的对齐方式。因此,它的大小是成员 char a
和 int b
的大小的总和,没有额外的填充字节。同时,aligned_struct
的地址将是 16
的倍数。
[09:22:17]sam@sam (*^~^*) ~/workbase/test> gcc -g test.c -o test
[09:22:24]sam@sam (*^~^*) ~/workbase/test> ./test
Size of aligned_struct: 16
Address of s: 0x7ffd0689c780
通过指定对齐方式,可以确保特定类型的数据在内存中按照要求的边界对齐,提高处理器对数据的访问效率。
但是请注意,如果对齐方式超过硬件和操作系统的支持范围,可能会导致编译错误。
上篇文章:【ARM 嵌入式 编译系列 11.1 – GCC attribute((aligned(x)))详细介绍】
上篇文章:【ARM 嵌入式 编译系列 11.3 – GCC attribute packed noreturn constructor 介绍】