Tip #2 Global Variables and Local Variables

In most cases, the use of global variables is not recommended. Use local variables whenever possible. If a variable is used only in a function, then it should be declared inside the function as a local variable.

In theory, the choice of whether to declare a variable as a global or local variable should be decided by how it is used.

If a global variable is declared, a unique address in SRAM will be assigned to this variable at program link time. Access to a global variable will typically need extra bytes (usually two bytes for a 16 bits long address) to get its address.

Local variables are preferably assigned to a register or allocated to stack if supported when they are declared. As the function becomes active, the function’s local variables become active as well. Once the function exits, the function’s local variables can be removed.

The table below shows the effect of global and local variables.

Table 1. Example of Global Variables and Local Variables
Global variables Local variables
C source code
#include <avr/io.h>
uint8_t global_1;
int main(void)
{ 
global_1 = 0xAA;
 PORTB = global_1;
}
#include <avr/io.h>
int main(void)
{
uint8_t local_1;
 local_1 = 0xAA;
PORTB = local_1;
}
AVR Memory Usage

Program: 104 bytes (1.3% Full)

(.text + .data + .bootloader)

Data: 1 bytes (0.1% Full)

(.data + .bss + .noinit)

Program: 84 bytes (1.0% Full)

(.text + .data + .bootloader)

Data: 0 bytes (0.0% Full)

(.data + .bss + .noinit)

Compiler optimization level -Os (Optimize for size) -Os (Optimize for size)

In the left example, we have declared a Byte-sized global variable. The output from the avr-size utility shows that we use 104 bytes of code space and 1 byte of data space with optimization level -Os (Optimize for size).

In the right example, after we declared the variable inside main() function as local variable, the code space is reduced to 84 bytes and no SRAM is used.