简体   繁体   中英

C array alignment check at compile time

I am trying to check an array alignment of 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: initializer element is not computable at load time. However, when I check the array alignment of 4, I don't get the error. The code below:

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

Language: C

Toolchain: arm-none-eabi-gcc

Compiler options: -mcpu=cortex-m3 -mthumb

Why is this happening?

如果您需要强制执行特定的对齐,则报告这适用于“arm-none-eabi-gcc”工具链:

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

The address of a static variable isn't known at compile time, it's only decided later by the linker. There is no suitable relocation for "address of a symbol modulo some arbitrary number" that the compiler can emit as the initialisation value for the linker to fix up, so it gives up. As Tom says in the comments, it can at least assume that the linker isn't going to violate the minimum required alignment for the type, so is able to optimise the expression away in that case.

The only way I think you could achieve this as-is would be to just declare it as extern bool aligned , then use some linker script black magic to define it with the appropriate value at link time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM