gcc “__attribute__((packed,aligned(4)))“的含义是什么

ybzsozfc  于 2022-11-13  发布在  其他
关注(0)|答案(3)|浏览(306)

它是C语言,写的是:

typedef struct __attribute__((packed, aligned(4))) Ball {
    float2 delta;
    float2 position;
    //float3 color;
    float size;
    //int arcID;
    //float arcStr;
} Ball_t;
Ball_t *balls;

请告诉我它的意思是什么,以及如何使用这个关键词。

e1xvtsh3

e1xvtsh31#

Before answering, I would like to give you some data from Wiki

Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.
To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.
If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)
wz8daaqr

wz8daaqr2#

  • packed意味着它将使用struct Ball的最小可能空间-即它将把字段塞在一起而不填充
  • aligned意味着每个struct Ball将在4字节边界上开始-即,对于任何struct Ball,其地址可以被4除

这些都是GCC扩展,不是任何C标准的一部分。

2wnc66cl

2wnc66cl3#

属性packed意味着编译器不会在struct的字段之间添加填充。填充通常用于使字段与其自然大小对齐,因为某些体系结构会对未对齐的访问施加惩罚,或者根本不允许。
aligned(4)表示结构应该对齐到可被4整除的位址。

相关问题