开发者

How can I align an element of a struct?

Is there any way to force an alignment of a particul开发者_开发知识库ar element of a struct using a GNUism?


Try 6.54.8 Structure-Packing Pragmas

For compatibility with Microsoft Windows compilers, GCC supports a set of #pragma directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The n value below always is required to be a small power of two and specifies the new alignment in bytes.

  1. #pragma pack(n) simply sets the new alignment.
  2. #pragma pack() sets the alignment to the one that was in effect when compilation started (see also command line option -fpack-struct[=<n>] see Code Gen Options).
  3. #pragma pack(push[,n]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment.
  4. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that #pragma pack([n]) does not influence this internal stack; thus it is possible to have #pragma pack(push) followed by multiple #pragma pack(n) instances and finalized by a single #pragma pack(pop).

Some targets, e.g. i386 and powerpc, support the ms_struct #pragma which lays out a structure as the documented __attribute__ ((ms_struct)).

  1. #pragma ms_struct on turns on the layout for structures declared.
  2. #pragma ms_struct off turns off the layout for structures declared.
  3. #pragma ms_struct reset goes back to the default layout.


http://gcc.gnu.org/onlinedocs/gcc-3.1.1/gcc/Type-Attributes.html

aligned (alignment)
This attribute specifies a minimum alignment (in bytes) for variables of the specified type. > For example, the declarations:
        struct S { short f[3]; } __attribute__ ((aligned (8)));
        typedef int more_aligned_int __attribute__ ((aligned (8)));


You can try the attribute aligned on the structure:

__attribute__((__aligned__(8)))


In addition to the things listed, you may also be interested in attribute((packed)) which attempts to lay out data without any padding -- essentially with alignment set to 1. This is useful when discribing the layout of data in a file or network protocol where padding bytes should just go away.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜