Search code examples
structalignmentpicmplabpic24

How to align variables in a struct for PIC24 chips?


I have this struct, but knowing that every 4th byte is not used in memory, I need to align the struct correctly in memory. I'm not exactly sure how to do this, though I know that I'm supposed to and I also know where it needs to happen.

typedef struct _vol_meta { 
        uint16_t crc;        // 2 bytes  
        uint8_t ver_major;   // 1 byte
        char pad1;           // need to align here - 1 byte

        uint16_t size;       // 2 bytes
        uint8_t ver_minor;   // 1 byte
        char pad2;           // need to align here  - 1 byte

        uint8_t pagenum;     // 1 byte
        uint8_t rownum;      // 1 byte
        char pad3[2];        // align here - 2 bytes

        uint8_t name[15];    // 15 bytes
        // not sure how I'm supposed to align the array of uint8_t vars?
} VOL_META;

Is there some kind of c data type like

align 2

That tells the compiler to skip the next 2 bytes or something? Kind of lost here.


Solution

  • You can use (surprise) 'aligned' attribute, like that:

    __ attribute __ ((aligned (2)) //word alignment

    xc16 user guide sect.8.12 is your friend.