# AVR local and global variable program size

I work on ATmega8 and I need to optimize my code as well as I can, because I am over limit and I saw something surprising. I have a few 8bit integers declared as global variables and a few 8bit integer declered as local variables. And in some case when I change global variable to local I get extra bytes of program and in same cases when I change local variable to global I also get extra bytes. Can anyone explain me why in same cases global variables generate smaller size of program and sometimes local variables do that?

• It has probably to do with compiler optimizations that may not be obvious. Without (minimalistic) example code, there is no good way to answer this. – Rev1.0 Jan 7 '15 at 7:29

Global variables are placed in the .data section of your program (if explicitly initialized) or in the .bss section (if not initialized). The initial values for global variables are copied over from flash upon start up by the __do_copy_data() function (added by the linker scripts if needed) and the initialization of the variables in .bss to zero (this is mandated by the C standard) is done by __do_clear_bss(). Your program includes symbols which tell it the size of these two segments. Code must be included to handle these events. Note that sometimes these variables can be bound to a register.
As a result, depending on the amount of code that needs to be added to the binary will change. For further details, you can see what is actually happening by disassembling your binary (avr-objdump is a good starting place) and by listing the symbols in the file (avr-nm).