__ attribute __ (packed) v / s GCC __ attribute __ ((aligned (x))

After GCC __attribute__(packed ) is packed into a byte boundary, alignment is used for this purpose: -

 u8 rx_buf[14] __attribute__((aligned(8))); struct S { short f[3]; } __attribute__ ((aligned (8))); 

there will be 16 bytes above the array, I'm right.

means that sizeof(rx_buff) will be 16 bytes. i.e. 2 byte alignment at the end

+7
source share
2 answers

The answer to your question is no. The aligned attribute does not resize the variables to which it applies, but the situation is slightly different for members of the structure. To quote the manual,

aligned

This attribute defines the minimum alignment for a variable field or structure, measured in bytes. For example, an ad:

 int x __attribute__ ((aligned (16))) = 0; 

causes the compiler to allocate the global variable x to a 16-byte boundary.

and

packed

A packed attribute indicates that the field of the variable or structure should have the smallest possible alignment - one byte for the variable, and one bit for the field, unless you specify a larger value with the aligned attribute.

Here is the structure in which the field x is packed, so that it immediately follows:

 struct foo { char a; int x[2] __attribute__ ((packed)); }; 

Note that the aligned attribute can change the memory structure of structures by inserting padding between members. Subsequently, the size of the structure will change. For example:

 struct t { uint8_t a __attribute__((aligned(16))); /* one byte plus 15 as padding here */ uint16_t b __attribute__((aligned(16))); }; 

would result in 15 bytes of padding after a , while the default alignment for the target architecture could lead to less. If you specified the packed attribute for the structure and lost aligned attributes, the structure will be 3 bytes in size. Here, in each case, it may look like the layout layout structure .

struct t with no attributes and default alignment on an 8-byte boundary:

 +-+-------+--+-------+ |a| |bb| | +-+-------+--+-------+ 

struct t when a and b are aligned on 16-byte boundaries:

 +-+---------------+--+---------------+ |a| padding |bb| padding | +-+---------------+--+---------------+ 

struct t when a and b have no alignment restrictions and t is packed:

 +-+--+ |a|bb| +-+--+ 
+14
source

there will be 16 bytes above the array, I'm right.

Wrong. The array is 14 bytes long; all that __attribute__((aligned)) does is provide any necessary padding outside the array to align it with an 8-byte boundary. It is impossible to predict with certainty where this supplement is, or how much it is there.

Thus, sizeof(rx_buf) will remain 14, just as it would be without alignment.

+3
source

All Articles