cancel
Showing results for 
Search instead for 
Did you mean: 

What is the proper syntax for aligning a struct, and a member within that struct?

ankes
Associate II

Hi,

I have a struct that looks like the following:

typedef struct {
    uint8_t statusbyte;
    uint8_t dmaBuffer[32];
} STRUCT_ReceptionBuffer;

The RM0091 instructs that source and destination addresses should be aligned on the data size. What I want to transfer to the buffer are 32-bit words (it is an I2S-to-USB-Audio conversion, and USB deals with bytes).

This means I need to align the struct. I am using the GCC compiler tools but the F0 HAL library also defines the __ALIGN_BEGIN and __ALIGN_END macros.

My question is, how and where should I place these macros in order for them to have the desired effect?

Does this look correct?

typedef __ALIGN_BEGIN struct {
    uint8_t statusByte;
    __ALIGN_BEGIN uint8_t dmaBuffer[32] __ALIGN_END;
} STRUCT_ReceptionBuffer __ALIGN_END;

Or would this be more correct?

 

typedef struct __ALIGN_BEGIN {
    uint8_t statusByte;
    __ALIGN_BEGIN uint8_t __ALIGN_END dmaBuffer[32];
} __ALIGN_END STRUCT_ReceptionBuffer ;

 

The complier does not seem to care much what I do. Even the following blatantly-wrong looking definition is completely fine?

typedef struct {
    uint8_t statusByte; __ALIGN_END
    uint8_t __ALIGN_END dmaBuffer[32];
} __ALIGN_END STRUCT_ReceptionBuffer;

Is this just a matter of trial and error? Or is it so that the compiler really doesn't care, and any errors caused by this only pop up during runtime?

1 REPLY 1
Pavel A.
Super User

It's not clear what do you actually want: 

A. define a structure so that members are properly aligned

B. Unpack byte-packed data to C struct with properly aligned members

C. Define a tightly packed structure (prevent adding pad bytes between struct members)  though some struct members won't be aligned.