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?
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.
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.
__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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With