__attribute__ 变量对齐

时间:2023-03-09 02:16:21
__attribute__ 变量对齐

http://blog.163.com/sunm_lin/blog/static/9192142200741533038695/

一.   __attribute__ ((aligned (n)))

该属性规定变量或结构体成员的最小的对齐格式,以字节为单位。例如:
int x __attribute__ ((aligned (16))) = 0;
编译器将以16字节(注意是字节byte不是位bit)对齐的方式分配一个变量。也可以对结构体成员变量设置该属性

二、__attribute__ ((aligned))

选择针对目标机器最大的对齐方式,可以提高拷贝操作的效率

三、__attribute__ ((packed))

使用该属性可以使得变量或者结构体成员使用最小的对齐方式,即对变量是一字节对齐,对域(field)是位对齐。

四、例子

struct foo {
  char a;
  int x[4] __attribute__ ((packed));
  };//17
struct bar8{
  char a;
  int x[4] __attribute__ ((aligned(8)));
  };//24
struct bar16 {
  char a;
  int x[4] __attribute__ ((aligned(16)));
  };//32
struct bar32{  char a;  int x[4] __attribute__ ((aligned(32)));
  };//64
struct bar {
  //char a;
  char x[4] __attribute__ ((aligned));
  };
struct bar_16 {
  char a;
  int x[4] __attribute__ ((aligned));
  };
[root@mip-123456 attribute]# ./var_attribute

sizeof(foo)=17

sizeof(bar)=16

sizeof(bar_16)=32

sizeof(bar8)=24

sizeof(bar16)=32

sizeof(bar32)=64