
1.指定内存默认对其参数:
__attribute__((packed)):按一字节对其
__attribute__((aligned(n))):从此之后默认按n字节对其
例如:
struct stu
{
int a;
char b;
}__attribute__((packed));
struct stu
{
int a __attribute__((aligned()));
char b;
};
例子:
#include <stdio.h> struct ss
{
char a __attribute__((aligned()));
int b;//① __attribute__((aligned(16)));
};//②__attribute__((aligned(16))); void main()
{
int i;
printf("%d\n", sizeof(struct ss));
struct ss s1 = {0x11, 0x55443322}; unsigned char *p = (unsigned char *)&s1; for(i=; i<sizeof(s1); i++)
{
printf("0x%x\n", *(p+i));
}
}
输出: 0x11
0xd1
0x98
0x0
0x22
0x33
0x44
0x55
0xe0
0xfc
0x98
0x0
0xf4
0xef
0x98
0x0
可以看出:
__attribute__((aligned(16)))在哪个域后面修饰哪个域(注意仅对此域有效,对其它域无效),更改了这个域的实际对齐参数,实际对齐参数决定了此域的起始存储位置,
再结合结构体的总大小必须能整除每一个域的最大对齐参数,因此可以推出来结构体的大小和内存的存储关系。
将结构体中注释掉掉的部分加上结构体大小就是32字节。
若只要③处,设定的只是结构体间对齐,结构体成员的存储顺序不变,只是结构体变长了。
1.1、结构体中含有位段的情况
#include <stdio.h> struct S3_1
{
char a;
short b : ;
short c : ;
short d : ;
int e : ;
int f : ;
}; struct S3_1 s3 = {0x11, , , , 0xf, 0x3f}; void main()
{
int i; printf("sizeof(s3)= %d\n", sizeof(s3)); unsigned char *p = (char *)&s3; for(i=; i<sizeof(s3); i++)
{
printf("0x%x\n", *(p+i));
}
}
①GNU的gcc编译器和Windows里的编译器的结果不一样,GNU的gcc输出:
sizeof(s3)=
0x11
0xff
0x3f
0x0
即最后面的int型的位段页归并到short里面一起用了。 ②在Window上gcc软件编译出输出:
sizeof(s3)=
0x11
0x0
0xf
0x0
0xff
0x3
0x0
0x0
和一般结构体对齐类似,只是其中的位是不是都占用而已。
2.__attribute__((weak))指定一个函数是若函数,消除链接时的multiple definition
例如:main.c
#include <stdio.h>
#define __weak __attribute__((weak))
void __weak func(void)
{
printf("%s\n", "void __atribute__(weak) func(void)");
}
void main()
{
func();
}
test.c中
#include <stdio.h>
void func(void)
{
printf("%s\n", "void func(void)");
}
3.__attribute__((regparm(0))):告诉gcc编译器该函数不需要通过任何寄存器来传递参数,参数只是通过堆栈来传递。
__attribute__((regparm(3))):告诉gcc编译器这个函数可以通过寄存器传递多达3个的参数,x86PC上,这3个寄存器依次为EAX、EDX 和 ECX。更多的参数才通过堆栈传递。这样可以减少一些入栈出栈操作,因此调用比较快。 ARM核默认是多于4个参数的会被保存在栈中
4.函数没有使用的参数后加__unused可防止编译器报警告
/*加上"__unused"可以防止编译器报警告:warning: unused parameter 'id' [-Wunused-parameter]*/
int led_module_open(const struct hw_module_t* module, const char* id __unused, struct hw_device_t** device) {
......
}