This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Padding at the end of aligned structure



On the c6000, we need to align and pad structures to 64 or 128 bytes (depending on the type of memory)  in order to implement software driven cache coherence.

The alignment can be accomplished with #pragma DATA_ALIGN().  However, this doesn't cause any padding at the end of the structure.  The padding is required in order to prevent the linker from putting anything else in the last cache line of the structure.

One way to add the padding is to put the desired structure into another structure eg:

typedef struct {

   . . .

} struct_to_pad;

typedef struct {

  struct_to_pad s;

  char pad[128 - (sizeof(struct_to_pad) & 0x7f)]

} padded_struct;

The above is messy because it requires modifying all the code that references the structure to either use a pointer indirection or to insert the struct.s.  It is also messy because, since pad[0] is illegal, there is no way to make "pad" go away if it turns out the structure already has an aligned length thus it wastes more memory than required.

Another way to achieve the padding is to put each such structure in a #pragma DATA_SECTION, and place each into its own output section.  This is messy due to plethora of output sections.

Are there any cleaner ways to achieve the padding?

  • You could try a GCC extension called unnamed fields.  Use a union to combine an unnamed structure with all the padding.  It would look like this ... 

    typedef union struct_to_pad {
        struct { // unnamed
            int f1;
            int f2;
            int f3;
                    ...
        };

        char pad[128]; // never used
    } struct_to_pad;

    struct_to_pad some_var;

    You can refer to members of the unnamed struct in normal fashion, i.e. some_var.f1, some_var.f2, etc.  More details from GCC docs are here.  

    If you insist on staying with perfectly portable ANSI standard C, then this is not for you.  You have to build with the --gcc switch.

    Thanks and regards,

    -George

  • I am looking for something that works with or without gcc extensions.  However, I like the creative solution.