11.11.2 Gaps Between Aligned Variables

Variables may be defined in C with the aligned attribute in order to specify special alignment requirements for modulo addressing or other purposes. Use of the aligned attribute will cause the variable to be allocated in a unique section. Since a unique section is never combined with other input sections, no alignment padding is necessary and the linker will allocate memory for the aligned variable in the most efficient way possible.

For example, the following sequence of C statements will not result in an alignment gap, because variable buf is allocated in a unique section automatically:

char c1,c2;
int i,j;
int __attribute__((aligned(256))) buf[128];

When allocating space for aligned variables in assembly language, the source code must also specify a section name. Unless the aligned variable is defined in a unique section, alignment padding may be inserted. For example, the following sequence of assembly statements would result in a large alignment gap, and should be avoided:

       .section my_vars,bss
       .global _var1,_var2,_buf
_var1: .space 2
_var2: .space 2
                         ; location counter is now 4
       .align 256
_buf:  .space 256
                         ; location counter is now 512

Re-ordering the statements so that _buf is defined first will not eliminate the gap. A named input section will be padded so that its length is a multiple of the requested alignment. This is necessary in order to guarantee correct alignment when multiple input sections with the same name are combined by the linker. Therefore reordering statements would cause the gap to move, but would not eliminate the gap.

Aligned variables in assembly must be defined in a unique section in order to avoid alignment padding. It is not sufficient to specify a section name that is used only once, because the assembler does not know if that section will be combined with others by the linker. Instead, the special section name * should be used. As explained in 5.1 Directives that Define Sections, the section name * instructs the assembler to create a unique section that will not be combined with other sections.

To avoid alignment gaps, the previous example could be written as:

       .section my_vars,bss
       .global _var1,_var2
_var1: .space 2
_var2: .space 2

       .section *,bss
       .global _buf
       .align 256
_buf:  .space 256

The alignment requirement for _buf could also be specified in the .section directive, as shown:

       .section *,bss,align(256)
       .global _buf
_buf:  .space 256