iDebD_gh
iDebD_gh

Reputation: 374

How to generate warning if a structure is declared without "__attribute__(align(8))"

I want the compiler to generate warning for me if structure declared without __attribute__(align(8)) .

For example, if a structure is declared like this:

struct my_float {
        float number;
}  __attribute__((aligned(8)));

It will not generate any warning. But if I declare another struct like this:

struct my_float {
        float number;
};

the compiler will generate a warning for me.

My working enveronment is linux/GCC.

Upvotes: 3

Views: 128

Answers (2)

user3727783
user3727783

Reputation:

From experience, it is not possible to do. This attribute specifies a minimum alignment (in bytes) for variables of the specified type.

struct S { short f[3]; } __attribute__ ((aligned (8)));
typedef int more_aligned_int __attribute__ ((aligned (8)));

force the compiler that each variable whose type is struct S or more_aligned_int is allocated and aligned at least on a 8-byte boundary.

Upvotes: 0

n0p
n0p

Reputation: 3496

I don't think you can automatically check this an ALL your structure, but you still can check your alignment manually with something like:

// x % 16 <=> x & (16-1)  (avoid using modulo operator)
#define MODULO_16_MASK 0xFU
ASSERT_COMPILE((sizeof(my_float) & MODULO_16_MASK) == 0);

This should trigger a warning at compiling if your structure is not aligned.

Upvotes: 1

Related Questions