Chinaunix首页 | 论坛 | 博客
  • 博客访问: 963395
  • 博文数量: 58
  • 博客积分: 10192
  • 博客等级: 上将
  • 技术积分: 1845
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-22 21:24
文章分类

全部博文(58)

文章存档

2011年(11)

2010年(12)

2009年(20)

2008年(15)

分类: C/C++

2010-01-22 17:12:17


在使用gcc的时候,特别是阅读源码的时候会看到
#pragma pack(n)
#pragma pack()

__attribute((aligned (8)))
__attribute__ ((packed));
下面写一下我的一点认识,不一定对,欢迎指正

这两种方式是gcc的c扩展,用来对齐的,包括栈对齐,变量地址对齐内存分配对齐,这几种方式一般来说gcc是兼容的

#pragma pack(n)
n的取值可以为1、2、4、8、16,在编译过程中按照n个字结对齐
#pragma pack()
取消对齐,按照编译器的优化对齐方式对齐
__attribute__ ((packed));
是说取消结构在编译过程中的优化对齐。
__attribute__ ((aligned (n)));
让所作用的成员对齐在n字节自然边界上,如果结构中有成员的长度大于n,则按照最大成员的长度来对。

我写了一个小测试程序来测验 struct a
{
int a;
char b;
char c;
}aa; /* 编译器默认对齐方式,32位机器,按照32位对齐 */

#pragma pack(1)
struct b
{
int a;
char b;
char c;
}bb; /* 按照8位对齐 */
#pragma pack()

#pragma pack(2)
struct c
{
int a;
char b;
char c;
}cc;/* 按照16位对齐 */
#pragma pack()

#pragma pack(4)
struct d
{
int a;
char b;
char c;
}dd; /* 按照32位对齐 */
#pragma pack()

#pragma pack(8)
struct e
{
int a;
char b;
char c;
}ee; /* 按照64位对齐 */
#pragma pack()

#pragma pack(16)
struct f
{
int a;
char b;
char c;
}ff; /* 按照128位对齐 */
#pragma pack()

struct m
{
int a;
char b;
char c;
}__attribute__((packed)) mm;
/* 取消编译器优化对齐,取实际长度 */

struct n
{
int a;
char b;
}__attribute__((aligned(1))) nn;
/* 按照32位对齐 */

struct o
{
long long a;
char b;
char c;
}__attribute__((aligned(2))) oo;
/* 按照64位对齐 */

struct p
{
int a;
char b;
char c;
}__attribute__((aligned(4))) pp;
/* 按照32位对齐 */


struct q
{
int a;
char b;
char c;
}__attribute__((aligned(8))) qq;
/* 按照64位对齐 */

struct r
{
int a;
char b;
char c;
}__attribute__((aligned(8*1024))) rr;
/* 按照512位对齐 */

int main()
{

printf("%d,%d,%d,%d,%d,%d\n",
   sizeof(aa),sizeof(bb),sizeof(cc),
   sizeof(dd),sizeof(ee),sizeof(ff));
printf("%d,%d,%d,%d,%d,%d\n",
   sizeof(mm),sizeof(nn),sizeof(oo),
   sizeof(pp),sizeof(qq),sizeof(rr));

return 0;
}


阅读(2141) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~