9.1.6 Tip #6 Access Types: Static

For global data, use the keyword "static" whenever possible. If global variables are declared with keyword "static", they can be accessed only in the file in which they are defined. It prevents an unplanned use of the variable (as an external variable) by the code in other files.

On the other hand, local variables inside a function should in most cases not be declared static. A static local variable's value needs to be preserved between calls to the function and the variable persists throughout the whole program. Thus it requires permanent data space (SRAM) storage and extra codes to access it. It is similar to a global variable except its scope is in the function where it's defined.

A static function is easier for the compiler to optimize, because its name is invisible outside of the file in which it is declared and it will not be called from any other files.

If a static function is called only once in the file with optimization (-O1, -O2, -O3, and -Os) enabled, the function will be optimized automatically by the compiler as an inline function and no assembler code is created to jump in and out of it. The table below shows the effect of static function.

Table 9-7. Example of Access Types: Static Function
Global Function (called once)Static Function (called once)
C source code
#include <avr/io.h>
uint8_t string[12] = {"hello world!"};
void USART_TX(uint8_t data);
int main(void)
{
uint8_t i = 0;
while (i<12) {
USART_TX(string[i++]);
}
}
void USART_TX(uint8_t data)
{
 while(!(UCSR0A&(1<<UDRE0)));
 UDR0 = data;
}
#include <avr/io.h>
uint8_t string[12] = {"hello world!"};
static void USART_TX(uint8_t data);
int main(void)
{
 uint8_t i = 0;
while (i<12) {
USART_TX(string[i++]);
}
}
void USART_TX(uint8_t data)
{
 while(!(UCSR0A&(1<<UDRE0)));
 UDR0 = data;
}
AVR Memory Usage

Program: 152 bytes (1.9% Full)

(.text + .data + .bootloader)

Data: 12 bytes (1.2% Full)

(.data + .bss + .noinit)

Program: 140 bytes (1.7% Full)

(.text + .data + .bootloader)

Data: 12 bytes (1.2% Full)

(.data + .bss + .noinit)

Compiler optimization level-Os (Optimize for size)-Os (Optimize for size)
Note: If the function is called multiple times, it will not be optimized to an inline function, because this will generate more code than direct function calls.