【问题标题】:Why g++ isn't performing structure packing here?为什么 g++ 不在这里执行结构打包?
【发布时间】:2015-12-24 20:15:25
【问题描述】:

考虑以下程序:

#include <iostream>
struct __attribute__((__packed__)) mystruct_A
{
   char a;
   int b;
   char c;
}x;
int main()
{
    std::cout<<sizeof(x)<<'\n';
}

来自this 我理解如下:

  • 结构填充抑制结构填充,填充时使用 对齐最重要,在空间最重要时使用包装。
  • 另一方面,结构打包阻止编译器执行 填充

我在 32 位环境中并使用 Windows 7 操作系统。链接问题的第一个答案说,上述代码将在 32 位架构上生成大小为 6 的结构。

但是当我使用 g++ 4.8.1 编译它时,它给了我 9 作为输出。那么,结构包装在这里没有完全发生吗? 为什么输出中有额外的 3 个字节? sizeof char 始终为 1。sizeof int 在我的编译器上为 4。所以,当结构被打包时,上面结构的 sizeof 应该是 1+4+1=6。

我在here 上试过。它给了我预期的输出 6。

处理器有什么作用还是只依赖于编译器?

【问题讨论】:

  • @JohnZwinck:如果您在 clang 上测试,请附上链接。
  • 我在我的 Macbook,64 位,Clang 3.5 上对其进行了测试。
  • @AndreyNasonov:不工作。它仍然给出 9 作为输出
  • 您使用的是 x86 CPU 吗?另外,哪个编译器? (g++ 到 windows 32 有两个不同的端口,mingw 和 mingw-w64)
  • 将 mingw-w64-i686-gcc 5.2 与此处提到的任何 __attribute__((packed)) 变体一起使用,我得到尺寸 9。使用 mingw-w64-i686-clang 3.7 和相同的属性,我得到尺寸 6 . 再次使用 g++ 和 #pragma pack(push, 1) / #pragma pack(pop) 在结构周围,我也得到大小 6。

标签: c++ structure padding sizeof memory-alignment


【解决方案1】:

打包的属性是broken on mingw32 compilers。另一种选择是使用 pragma pack:

#pragma pack(1)
struct mystruct_A {
  char a;
  int b;
  char c;
} x;

【讨论】:

    【解决方案2】:

    这里的解决方案对我有用:https://wintermade.it/blog/posts/__attribute__packed-on-windows-is-ignored-with-mingw.html,即将-mno-ms-bitfields 添加到编译器标志中。

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      相关资源
      最近更新 更多