BertVano BertVano - 23 days ago 4
C Question

What uses up more space in FLASH? static variable or global variable

As the title says, what uses up more space in FLASH (in an STM32 ┬ÁC for example)? Declaring a global variable or declaring a static variable inside a function? Or do they take equal space? Both variables are available throughout the whole runtime of the program in my understanding. Just their scopes are different.


You can have 0-initialized global and static variables. Those normally take up no flash, because they are placed in memory location which is allocated and zeroed when program starts and does not come from flash.

You can initialize the variables with value too. In that case they are placed in the initalized data segment, so take up space from flash according to size of the data type.

Static variables inside functions you can also initialize with code. That initializaton must happen at runtime, but can happen only once, so it actually generates more code, which will in almost any case take more space than the size of the data (not necessarily, at least if you initialize a large enough struct with a function return value). You can do almost same for non-const global variables too, you just need to leave them 0-initialized orignally and put assignment (for example) at the start of main(), where it takes the same space as initialization of function scope static variable by code takes elsewhere.

Conclusion, both global and function-scope static variables take up same amount of space.

Above assumes "global variable" in embedded context, or as a file-scope static variable. If it is exported global symbol in a dynamically linkable executable, then relocation information for that symbol will take some space in the executable binary. However, I don't think given example system supports or uses relocatable executables.