C语言#pragma pack(n)和__attribute__((aligned(m)))的介绍

本文介绍了C语言中#pragmapack(n)和__attribute__((aligned(m)))指令的使用方法,通过具体实例展示了如何控制结构体成员变量的对齐方式及结构体本身的对齐方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


C语言#pragma pack(n)和__attribute__((aligned(m)))的介绍


一、简单介绍

1、#pragma pack(n)告诉编译器结构体或类内部的成员变量相对于第一个变量的地址的偏移量的对齐方式,缺省情况下,编译器按照自然边界对齐,当变量所需的自然对齐边界比n大 时,按照n对齐,否则按照自然边界对齐;#pragma pack () /*取消指定对齐,恢复缺省对齐*/

2、__attribute__((aligned(m)))告诉编译器一个结构体或者类或者联合或者一个类型的变量(对象)分配地址空间时的地址对齐方式。也就是所,如 果将__attribute__((aligned(m)))作用于一个类型,那么该类型的变量在分配地址空间时,其存放的地址一定按照m字节对齐(m必 须是2的幂次方)。并且其占用的空间,即大小,也是m的整数倍,以保证在申请连续存储空间的时候,每一个元素的地址也是按照m字节对齐。


二、实例测试学习

1、例子一,下面的这个例子,如果按自然边界对齐,f5的偏移地址应该是0x10,但设置#pragma pack(4)后f5的偏移地址后变为0xc

测试c代码:

#include<stdio.h>
#pragma pack(4) 
//#pragma pack()//取消1字节对齐,恢复为默认4字节对齐
typedef struct{

unsigned int f1;

unsigned char f2;

unsigned char  f3;

unsigned int f4;

unsigned long int f5;

//}__attribute__((aligned(1024))) ts;
//}__attribute__((packed)) ts;
}ts;
int main()

{
	  int n ;
      ts st1;  
      printf("\nsizeof(unsigned int)=%d , sizeof(unsigned long int)=%d\n",sizeof(unsigned int),sizeof(unsigned long int));
  
      printf("Allocate f1 on address: 0x%x\n",&(st1.f1));

      printf("Struct size is: %d\n",sizeof(ts));

      printf("Allocate f1 on address: 0x%x\n",&(((ts*)0)->f1));

      printf("Allocate f2 on address: 0x%x\n",&(((ts*)0)->f2));

      printf("Allocate f3 on address: 0x%x\n",&(((ts*)0)->f3));

      printf("Allocate f4 on address: 0x%x\n",&(((ts*)0)->f4));

      printf("Allocate f5 on address: 0x%x\n",&(((ts*)0)->f5));
      return 0;

}

编译&执行



2、测试实例二,将一个结构体的对齐方式设置为__attribute__((aligned(1024))),你会发现,原本大小不到1024个字节的结构体,实际的占用的空间会是1024.其存放的地址一定按照1024字节对齐(即1024的倍数)。

测试c代码

#include<stdio.h>
//#pragma pack(4)
//#pragma pack(4) //取消1字节对齐,恢复为默认4字节对齐
//#pragma pack()
typedef struct{

unsigned int f1;

unsigned char f2;

unsigned char  f3;

unsigned int f4;

unsigned long int f5;

}__attribute__((aligned(1024))) ts;
//}__attribute__((packed)) ts;
//}ts;
int main()

{
	  int n ;
      ts st1;  
      printf("\nsizeof(unsigned int)=%d , sizeof(unsigned long int)=%d\n",sizeof(unsigned int),sizeof(unsigned long int));
  
      printf("Allocate f1 on address: 0x%x\n",&(st1.f1));

      printf("Struct size is: %d\n",sizeof(ts));

      printf("Allocate f1 on address: 0x%x\n",&(((ts*)0)->f1));

      printf("Allocate f2 on address: 0x%x\n",&(((ts*)0)->f2));

      printf("Allocate f3 on address: 0x%x\n",&(((ts*)0)->f3));

      printf("Allocate f4 on address: 0x%x\n",&(((ts*)0)->f4));

      printf("Allocate f5 on address: 0x%x\n",&(((ts*)0)->f5));
      return 0;

}

 编译&执行


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值