Visual Studio 中 pragma pack 指令的范围

2024-01-01

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

pack 在第一个结构体、联合体或类声明处生效 看到杂注后

因此,对于以下代码:

#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

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


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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Visual Studio 中 pragma pack 指令的范围 的相关文章

随机推荐