Gustavo
Gustavo

Reputation: 1019

Struct packing in different memory sections on AVR

There is the following struct:

typedef struct {
    uint8_t val1;
    uint16_t val2;
}some_config_type;

some_config_type EEMEM config = {
    .val1 = 20,
    .val2 = 2000
};

The config is stored in eeprom memory where I want to load it from. I'm not sure if there is a rule in avr gcc or C in common which guarantees that bot struct layouts will be the same when I use eeprom_read_block for copy into ram which is another memory section. I want to make sure that this does not break under any circumstances and the memory layout is the same and not depending on the section.

Upvotes: 0

Views: 824

Answers (1)

Lundin
Lundin

Reputation: 213852

The AVR is a 8 bit MCU so it has no alignment requirements as far as the CPU is concerned. There should be no struct padding on this specific system.

Flash and EEPROM may have alignment requirements, related to their memory sectors, but that is only relevant to the drivers writing to such areas. It doesn't affect how the compiler allocates struct.

I'm not sure if there is a rule in avr gcc or C in common which guarantees that bot struct layouts will be the same when I use eeprom_read_block for copy into ram which is another memory section.

Yes, a struct will always have the same memory layout across the program, no matter where it is stored. This is guaranteed by the C standard.

RAM and EEPROM might have different alignment requirements, but there's no "magic behind the lines" handling that - you'd have to handle it manually for such cases, when coding the flash/EEPROM driver.

Upvotes: 8

Related Questions