C++ #pragma pack指令简析

  • Post author:
  • Post category:其他


微软官方文档说

#pragma pack

指令的作用是为结构、联合和类成员指定 pack 对齐。的主要作用就是改变编译器的内存对齐方式,这个指令在网络报文的处理中有着重要的作用,

#pragma pack(n)

是他最基本的用法,其作用是改变编译器的对齐方式, 不使用这条指令的情况下,编译器默认采取

#pragma pack(8)

也就是8字节的默认对齐方式,n值可以取

1, 2, 4, 8, 16

中任意一值。

来写一个程序试下:

#include <iostream>
#include <stddef.h>
using namespace std;

struct Test{
short a;//2
int b;//4
double c;//8
long d;//8
};

#pragma pack(2)
struct S {
short a;//2
int b;//4
double c;//8
long d;//8
};
int main()
{
cout << offsetof(Test, a) << endl;
cout << offsetof(Test, b) << endl;
cout << offsetof(Test, c) << endl;
cout << offsetof(Test, d) << endl;
cout << "---------------" << endl;
cout << offsetof(S, a) << endl;
cout << offsetof(S, b) << endl;
cout << offsetof(S, c) << endl;
cout << offsetof(S, d) << endl;
system("pause");
return 0;
}

该程序在win32位PC机下打印结果如下:

0
4
8
16
---------------
0
2
6
14



版权声明:本文为xiangxianghehe原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。