Search code examples
cgcccompiler-errorsvolatile

how to place global variables placed adjacent? (without setting it at linker script)


I want to place 3 variables 32 bytes apart adjacent with each other. This is for debugging, a suspicious behavior.
For this line of C code (sparc, bare-metal, defining a global variable outside a function.)

int __attribute__ ((aligned (32))) xx0, layer_complete, xx1;

With just this code, the variables xx0, xx1, layer_complete are aligned to 32 byte but just after layer_complete, there are some variables placed. I want only one variable to be placed in a 32 bit range. (having said that, I have an idea of using union. but I'm curious if I can do it without union).

ADD : I tried this with union (to make some space after layer_complete)

union ttt {
    int layer_complete;
    int a[8]; // to make it 32 bytes
} __attribute__((aligned(32))) lc_union;
#define layer_complete lc_union.layer_complete

inspecting program.map I can see layer_complete is 32 byte aligned and the following 28 bytes are not used (of course).


Solution

  • This should do the trick:

    typedef struct
    {
       int _Alignas(32) xx0;
       int _Alignas(32) layer_complete;
       int _Alignas(32) xx1;
    } thing;
    ...
    thing t;
    

    If you for some reason is using a very old version of gcc (pre-C11, 4.x something or older), then you can also use non-standard __attribute__ ((aligned (32))).

    Since this is just for debugging purposes, you could make macros such as #define xx0 t.xx0 to make the struct compatible with what you already got.