9

#pragma packVisual C++中对齐的范围是什么?API 参考 https://msdn.microsoft.com/en-us/library/vstudio/2e70t5y1%28v=vs.120%29.aspx 说:

pack 在看到 pragma 后的第一个结构、联合或类声明时生效

因此,对于以下代码:

#include <iostream>

#pragma pack(push, 1)

struct FirstExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};

struct SecondExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};


void main()
{
   printf("Size of the FirstExample is %d\n", sizeof(FirstExample));
   printf("Size of the SecondExample is %d\n", sizeof(SecondExample));
}

我已经预料到:

Size of the FirstExample is 5
Size of the SecondExample is 8

但我收到了:

Size of the FirstExample is 5
Size of the SecondExample is 5

这就是为什么我有点惊讶,我非常感谢你能提供的任何解释。

4

3 回答 3

8

仅仅因为它“在第一个结构上生效”并不意味着它的效果仅限于第一个结构。#pragma pack以预处理器指令的典型方式工作:它从激活点“无限期地”持续,忽略任何语言级别的范围,即它的效果传播到翻译单元的末尾(或直到被另一个覆盖#pragma pack)。

于 2015-06-24T19:19:05.073 回答
6

它在看到 pragma 后的第一个结构、联合或类声明时生效,并持续到第一次遇到 #pragma pack(pop) 或另一个持续到其 pop-counterpart 的 #pragma pack(push)。

(push 和 pops 通常成对出现)

于 2015-06-24T19:14:16.830 回答
4

你应该#pragma pack(pop)先打电话SecondExample

#include <iostream>
#pragma pack(push, 1)

struct FirstExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};

#pragma pack(pop)

struct SecondExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};


void main()
{
 printf("Size of the FirstExample is %d\n", sizeof(FirstExample));
 printf("Size of the SecondExample is %d\n", sizeof(SecondExample));
}
于 2015-06-24T19:18:31.490 回答