Search code examples
cgccalignment

How to specify default global variable alignment for gcc?


How do I get rid of alignment (.align 4 below) for all global variables by default with GCC, without having to specify __attribute__((aligned(1))) for each variable?

I know that what I ask for is a bad idea to apply universally, becuase on some architectures an alignment of 1 wouldn't work, because e.g. the CPU is not able to dereference an unaligned pointer. Bit in my case I'm writing an i386 bootloader, and unaligned pointers are fine (but slower) there.

Source code (a.c):

__attribute__((aligned(1))) int answer0 = 41;
int answer = 42;

Compiled with: gcc -m32 -Os -S a.c

Assembly output (a.s):

    .file   "a.c"
    .globl  answer
    .data
    .align 4
    .type   answer, @object
    .size   answer, 4
answer:
    .long   42
    .globl  answer0
    .type   answer0, @object
    .size   answer0, 4
answer0:
    .long   41
    .ident  "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4"
    .section        .note.GNU-stack,"",@progbits

The flag gcc -fpack-struct=1 changes the alignment of all struct members and structs to 1. For example, with that flag

struct x { char a; int b; };
struct y { int v : sizeof(char) + sizeof(int) == sizeof(struct x); };
struct z { int b; };
struct x x = { 1, 1 };
int i = 42;
struct z z = { 2 };

compiles to no alignment for variables x' andz', but it still has an .align 4 for the variable i (of type int). I need a solution which also makes int i = 42; unaligned, without having to specify something extra for each such variable.


Solution

  • Most probably gcc doesn't have such a flag which can change the default alignment of global variables.

    gcc -fpack-struct=1 can be a workaround, but only for global variables which happen to be of struct type.

    Also post-processing the .s output of gcc and removing (some of) the .align lines could work as a workaround.