gcc-arm-none-eabi-4_9+Cortex-M4F环境下const char变量与单元素数组内存对齐差异原因及1字节对齐实现方法
Great question—this is a common gotcha when working with ARM Cortex-M toolchains, especially when you’re trying to optimize memory usage. Let’s break down what’s happening and how to fix it:
Why does const char bb[1] default to 4-byte alignment?
The Cortex-M4F is a 32-bit core, and the gcc-arm-none-eabi-4_9 toolchain applies alignment rules optimized for this architecture:
- For scalar variables like
const char aa = 0;, the compiler uses the minimum required alignment for the type (1 byte forchar). Since you’re only accessing a single byte, there’s no performance benefit to aligning it to a larger boundary. - For arrays, even single-element ones, the toolchain defaults to aligning them to the core’s natural word size (4 bytes). This is a heuristic optimization: arrays are often accessed in bulk or via pointer arithmetic, and 4-byte alignment avoids unaligned access penalties (even if your array only has one element, the compiler treats it as a potentially bulk-accessible structure).
In your Case B, the *fill* 0x0005dbb1 0x3 line shows the compiler adding 3 bytes of padding after aa to push bb to the next 4-byte boundary (0x0005dbb4, which is divisible by 4).
How to make const char bb[1] align to 1 byte like scalar variables?
As you demonstrated in Case C, the simplest way is to explicitly override the alignment using GCC’s __attribute__ ((aligned (1))) attribute. This tells the compiler to ignore the default array alignment and use the minimum 1-byte alignment instead.
Your working declaration looks like this:
const char bb[1] __attribute__ ((aligned (1))) = {1};
This forces the array to sit immediately after the previous variable with no padding, matching the behavior of scalar const char variables.
If you need this behavior for multiple arrays, you could also use the compiler flag -falign-arrays=1 to set 1-byte alignment globally for all arrays. Just be aware this will affect every array in your code, which might not be desirable if some arrays benefit from 4-byte alignment for performance.
Is 4-byte alignment the default for all char arrays on this platform?
Yes, for gcc-arm-none-eabi-4_9 targeting Cortex-M4F, arrays of any type (including char) default to 4-byte alignment. This is a target-specific optimization designed to align with the 32-bit memory access patterns typical of embedded ARM systems.
内容的提问来源于stack exchange,提问作者yyd

