开发者

Structure alignment in GCC (should alignment be specified in typedef?)

Sorry for a stupid question, but if I need to ensure the alignment of a structure / class / union, should I add attribute((aligned(align))) to typedef declaration?

class myAlignedStruct{} __attribute__ ((aligned(16)));
typedef myAlign开发者_运维百科edStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?


should I add attribute((aligned(align))) to typedef declaration?

No... typedefs are just pseudonyms or aliases for the actual type specified, they don't exist as a separate type to have different alignment, packing etc..

#include <iostream>

struct Default_Alignment
{
    char c;
};

struct Align16
{
    char c;
} __attribute__ ((aligned(16)));

typedef Align16 Also_Align16;

int main()
{
    std::cout << __alignof__(Default_Alignment) << '\n';
    std::cout << __alignof__(Align16) << '\n';
    std::cout << __alignof__(Also_Align16) << '\n';
}

Output:

1
16
16


The accepted answer ("No") is correct, but I wanted to clarify one potentially misleading part of it. I'd add a comment but need to format some code; hence the new answer.

typedefs are just pseudonyms or aliases for the actual type specified, they don't exist as a separate type to have different alignment, packing etc..

This is incorrect, at least for GCC (the OP's compiler), and GHS. For example, the following compiles without errors, showing that the alignment can be attached to a typedef.

The perverse alignment (greater than the size of the object) is merely for shock and amusement value.

#define CASSERT( expr ) { typedef char cassert_type[(expr) ? 1 : -1]; }

typedef __attribute__((aligned(64))) uint8_t aligned_uint8_t;

typedef struct
{
    aligned_uint8_t t;
} contains_aligned_char_t;

void check_aligned_char_semantics()
{
    CASSERT(__alignof(aligned_uint8_t) == 64);
    CASSERT(sizeof(aligned_uint8_t) == 1);
    CASSERT(sizeof(contains_aligned_char_t) == 64);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜