Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

alignment

gcc

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 myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?
like image 602
Anonymous Avatar asked Jul 22 '11 05:07

Anonymous


People also ask

What is a typedef struct?

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.

What is aligned attribute in C?

The aligned variable attribute specifies a minimum alignment for the variable or structure field, measured in bytes. The aligned attribute only increases the alignment for a struct or struct member. For a variable that is not in a structure, the minimum alignment is the natural alignment of the variable type.

What does __ Attribute__ packed )) Meaning?

__attribute__((packed)) variable attribute The packed variable attribute specifies that a variable or structure field has the smallest possible alignment. That is, one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.


1 Answers

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
like image 199
Tony Delroy Avatar answered Oct 03 '22 08:10

Tony Delroy