Place a variable in AVR EEPROM with the EEMEM attribute
Place a variable in AVR EEPROM with the EEMEM attribute from avr-libc 2.2, read it with eeprom_read_byte, and upload the .eep file too.
On an AVR the EEPROM is a separate address space, so a normal variable cannot live there. avr-libc marks a variable for it with the EEMEM attribute from avr/eeprom.h. The compiler puts it in the .eeprom section, assigns an EEPROM address and keeps your initial value for a separate image file. You read and write it with the eeprom_* functions, which take the address of the variable.
#include <avr/eeprom.h>
#include <stdint.h>
#include <stdio.h>
uint8_t EEMEM saved_level = 7;
uint16_t EEMEM saved_count;
int main(void)
{
uint8_t level = eeprom_read_byte(&saved_level);
printf("level=%u\n", level);
eeprom_update_word(&saved_count, 1234);
}level=7The initial value 7 only reaches the chip if you program the EEPROM image. The build produces it as a separate file: avr-objcopy -j .eeprom --change-section-lma .eeprom=0 -O ihex prog.elf prog.eep, and avrdude uploads it with -U eeprom:w:prog.eep:i. A normal flash upload does not touch the EEPROM, and an erased EEPROM reads 0xFF, so without the .eep step the program would print level=255. Use eeprom_update_* rather than eeprom_write_*, which skips the write when the byte is the same and saves cycles of wear. See the avr-libc manual page for <avr/eeprom.h>.
Writes take milliseconds and the EEPROM wears out, so do not write on every loop. An erase on chip programming may also clear the EEPROM, depending on the EESAVE fuse.