Search code examples
c++gccc++11alignmentlibstdc++

attributes in the definition of max_align_t of libstdc++


max_align_t is defined as follows in libstdc++:

typedef struct {
  long long __max_align_ll __attribute__((__aligned__(__alignof__(long long))));
  long double __max_align_ld __attribute__((__aligned__(__alignof__(long double))));
} max_align_t;

Aren't those attributes redundant? I got the same result without those attributes:

typedef struct {
  long long __max_align_ll;
  long double __max_align_ld;
} max_align_t;

The question is 'Is there any reason those attributes specified?.'


Solution

  • The attributes force the type to be correctly aligned if it is included as a member of another struct and compiled with -fpack-struct or a packing #pragma

    e.g.

    typedef struct {
      long long __max_align_ll __attribute__((__aligned__(__alignof__(long long))));
      long double __max_align_ld __attribute__((__aligned__(__alignof__(long double))));
    } max_align_t;
    
    typedef struct {
      long long __max_align_ll;
      long double __max_align_ld;
    } max_align2_t;
    
    struct A {
      char c;
      max_align_t ma;
    };
    
    struct A2 {
      char c;
      max_align2_t ma;
    };
    
    static_assert( sizeof(A) == sizeof(A2), "" );
    

    With -fpack-struct the assertion fails, showing that the attributes prevent the max_align_t type being incorrectly aligned.