简体   繁体   English

为什么这个结构不会打包?

[英]Why would this struct not pack?

Perhaps I am misunderstanding something regarding the nature of the "packed" attribute, but it is my understanding that the below struct should pack to 16 bytes, rather than the normally padded 24 bytes.也许我误解了“打包”属性的性质,但我的理解是下面的结构应该打包到 16 个字节,而不是通常填充的 24 个字节。 I can verify that the packed attribute is being applied (in general) as I have another struct defined in the same header file that is packed down from 16 bytes to 10 bytes.我可以验证是否应用了打包属性(通常),因为我在同一个头文件中定义了另一个结构,该结构从 16 字节压缩到 10 字节。 Is there any reason why the compiler would ignore the attribute without indicating via a warning?编译器是否有任何理由忽略该属性而不通过警告指示?

To clarify, when I say that it does not appear to be packing, I am basing that off of the output of sizeof(foo) which returns 24 rather then the expected 16. The code in question is within a simple/crude custom kernel with very limited tools at the moment, so I have been relying on basic debugging via printing to screen.澄清一下,当我说它似乎没有打包时,我基于 sizeof(foo) 的输出,它返回 24 而不是预期的 16。有问题的代码在一个简单/粗略的自定义内核中目前非常有限的工具,所以我一直依靠通过打印到屏幕进行基本调试。

I am using GCC 10.3.0 (on ubuntu).我正在使用 GCC 10.3.0(在 ubuntu 上)。

    typedef struct {
      uint16_t m1;
      uint16_t m2;
      uint8_t m3;
      uint8_t m4;
      uint16_t m5;
      uint32_t m6;
      uint32_t m7;
    }__attribute__((packed)) foo;

正如 paddy 所指出的,问题是uint64_t类型定义不正确,这导致每个额外的 4 个字节,而结构中的 2 个导致额外的 8 个字节。

A cautionary note: while __attribute__((packed)) is defined by GCC, this is an implementation defined extension , and not part of the standard C language.警告:虽然__attribute__((packed))是由 GCC 定义的,但这是一个实现定义的扩展,而不是标准 C 语言的一部分。

As such, while this should work as intended with GCC (or GCC derivatives), it will not necessarily work on any other compiler - therefore, if you are relying on the packing, you need to make sure that it is packing as you expect it.因此,虽然这应该在 GCC(或 GCC 衍生产品)上按预期工作,但它不一定适用于任何其他编译器 - 因此,如果您依赖打包,则需要确保它按预期打包.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM