I want to know what actually going under the hood,how compiler treats static variables. Unlike auto variable, static variable\'s value persist even after the end of block bu
Unlike local variables which go on stack, static variables are kept in special data segments. Which segment your static variable goes to depends on if they are 0 initialized or not. 0 initialized static data goes in .BSS (Block Started by Symbol), non 0 initialized data goes in .DATA.
If you want to learn more what about different segments within executable files, this Wikipedia entry is a good starting point. I also highly recommend Chapter 7 in Computer Systems: A Programmer's Perspective by Randal E. Bryant and David R. O'Hallaron.
I'm describing here one particular scenario. You need to take into account that details will vary from one architecture to another, from one OS to another, so on and so forth. However, the general layout of executable files remains as described. Exciting stuff indeed!
EDIT:
The author kindly asked me to clarify:
what is the point of dividing the 0 initialized variable to .bss and non 0 initialized to .data?
From Section 7.4 in Computer Systems: A Programmer's Perspective on the .BSS section:
This section occupies no actual space in the object file; it is merely a place holder. Object file formats distinguish between initialized and uninitialized variables for space efficiency: uninitialized variables do not have to occupy any actual disk space in the object file.
And, from Wikipedia:
Typically only the length of the .BSS section, but no data, is stored in the object file. The program loader allocates and initializes memory for the bss section when it loads the program.
To summarize: it's a mechanism for saving memory.