这段 C++ 代码的作用是什么?怎么会有__attribute__
呢?
struct foo { double t[4] __attribute__((aligned(64))); };
最佳答案
来自http://gcc.gnu.org/onlinedocs/gcc-4.1.2/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)));
force the compiler to insure (as far as it can) that each variable whose type is struct S or more_aligned_int will be allocated and aligned at least on a 8-byte boundary. On a SPARC, having all variables of type struct S aligned to 8-byte boundaries allows the compiler to use the ldd and std (doubleword load and store) instructions when copying one variable of type struct S to another, thus improving run-time efficiency.
Note that the alignment of any given struct or union type is required by the ISO C standard to be at least a perfect multiple of the lowest common multiple of the alignments of all of the members of the struct or union in question. This means that you can effectively adjust the alignment of a struct or union type by attaching an aligned attribute to any one of the members of such a type, but the notation illustrated in the example above is a more obvious, intuitive, and readable way to request the compiler to adjust the alignment of an entire struct or union type.
因此,该代码实际上要求编译器在 64 字节边界上对齐 t
(通常,它会在 8 字节边界上对齐,因为它是一个 双
)。
关于带有 __attribute__ 的 C++ 结构体代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774689/