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.
Global Function (called once) | Static Function (called once) | |
---|---|---|
C source code |
|
|
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) |