结构使用GNU GCC中的__attribute __((__ packed__))打包

Ani*_*aul 2 c structure packing padding

我们知道这_attribute__((__packed__))意味着(最有可能)"不插入任何填充物来加快速度",也可能意味着"不要插入任何对齐以保持对齐".

struct structure2
{
   int id1 __attribute__((__packed__));
   char name __attribute__((__packed__));
   int id2 __attribute__((__packed__));
   char c __attribute__((__packed__));
   float percentage __attribute__((__packed__));
};
struct structure2 b;
printf("   \n\nsize of structure2 in bytes : %d\n", sizeof(b));// output = 20
Run Code Online (Sandbox Code Playgroud)

为什么不删除所有填充(输出= 14)?

Ker*_* SB 9

尝试:

struct __attribute__((__packed__)) structure2
{  //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^
   int id1;
   char name;
   int id2;
   char c;
   float percentage;
};
Run Code Online (Sandbox Code Playgroud)

打包一个字段没有意义.正如您自己所说,填充是关于字段之间的关系,因此该属性属于结构本身,而不属于其字段.

  • `__attribute __((packed))`也可以放在结束`}`和`;`之间,因此:`struct structure2 {...} __attribute __((packed));` (2认同)