The text I am reading says:
Global variables are located in executable image, so using number of global variables will increase the size of executable image.
Questions:
-
What does ‘located in executable image’ mean? From what I have read the global variables are located in the ‘data’ section of the executable. I presume that local variable initialisation instructions are stored in the ‘text’ section. So why don’t the local variable initialisation instructions take up about the same amount of space as the global variables do?
-
By executable, does it mean here the executable loaded into the memory or the executable that is only on the non-volatile memory? Will the global variables also take up more space for executable that is not loaded into the RAM?
-
Are there books or concise reading resources I may refer to that will help me with such lower level concepts?
I expected the size of the local variable initialization instructions to take up the same amount of space in executable as global variables do. Consider the following program:
#include <stdlib.h>
int global_var = 10
int main(void){
int local_var = 20;
return EXIT_SUCCESS;
}
When converted to machine level executable (assuming its not loaded into memory/not a process), I assume both definition and initialisation of global_var
and local_var
will be encoded as machine level code, albeit in different sections (data and text) of executable. So why will global_var
take up more space?
Quorthon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
All objects take up memory. If it is initialized, it must be stored somewhere.
However, not all object declarations are equal. Your example there has a global_var
that must have a realized int
object space somewhere modifiable in your program. That takes space.
But the local local_var
is very likely optimized out of existence by your compiler, since the compiler can prove to itself that it is never used (or only used in a context not requiring an actual stored int
object anywhere in memory).
The only things necessary are the initial values, which must exist somewhere in the program. Again, since local_var
gets elided, so does the requirement to store its initial value.