I want to know that what happens inside the compiler... like whether it store global variable at different location.
-
4Get yourself a good book on basics of compiler. Might get some resources here - http://stackoverflow.com/questions/1669/learning-to-write-a-compiler – CCoder Nov 12 '12 at 11:07
-
Get yorself any book on C or C++. Got the the chapter about *scope*. – Benjamin Bannier Nov 12 '12 at 11:07
-
@honk a variable can be a global but not be in the global scope... scope and lifetime are different. (assuming that's what you meant) – Luchian Grigore Nov 12 '12 at 11:08
-
@LuchianGrigore: I was pretty sure that random book would mention `static` near that spot, but yes, my comment wasn't too helpful. – Benjamin Bannier Nov 12 '12 at 11:24
3 Answers
The Wikipedia page on symbol tables can provide you a basic understanding.
http://en.wikipedia.org/wiki/Symbol_table
In computer science, a symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is associated with information relating to its declaration or appearance in the source, such as its type, scope level and sometimes its location.
[...]
A common implementation technique is to use a hash table implementation. A compiler may use one large symbol table for all symbols or use separated, hierarchical symbol tables for different scopes.
Emphasis mine.
It knows that the variable is global or local by how you declare it.
//declared at namespace scope - global
extern int x;
int main()
{
//declared inside a method - local
int y;
};

- 253,575
- 64
- 457
- 625
Generally there are 4 scopes of any variables.
Using extern
keyword you are making that variable extern explicitly.(by default global variables are extern
)
Using static
limiting the variable or function scope to it's current file
In accordance of that the memory are allocated in different segments
global: visible in more than one source file
-- data segement(also differs whether initialised or uninitialized)
local : visible with in { } it also called function(){} scope
-- on stack
block : {} inside any function another scope of block valiables with in {}
-- on stack if with in function
file : making static variable is limited to it's file scope or
current translation unit. -- again data section

- 9,018
- 8
- 39
- 59