Checking alignment of a C array at compile time

I am trying to check the alignment of array 8 at compile time. This is the code:

// File scope uint32_t pool[1024]; bool aligned = (((uintptr_t) pool) % 8) == 0; 

I get this error: the initialization element is not evaluated at boot time. However, when I check the alignment of array 4, I do not get an error. Code below:

 // File scope uint32_t pool[1024]; bool aligned = (((uintptr_t) pool) % 4) == 0; 

Language: C

Tool Chain: arm-none-eabi-gcc

Compiler Options: -mcpu = cortex-m3 -mthumb

Why is this happening?

+5
source share
2 answers

The address of the static variable is unknown at compile time, this is decided later by the linker. There is no suitable move for "the address of a character modulo some arbitrary number" that the compiler can emit as an initialization value for the linker to eliminate it, so it refuses. As Tom says in the comments, he can at least assume that the linker is not going to break the minimum required alignment for the type, so he can optimize the expression in this case.

The only way I could achieve this as it is is simply to declare it as extern bool aligned , and then use some black magic linker script to determine it with the appropriate value during the link.

+3
source

If you need to enforce a certain alignment, this is reported to work for the arm-none-eabi-gcc toolchain:

uint32_t pool[1024] __attribute__((aligned(8)));

+5
source

All Articles