Conceptually, the initialisation of global variables happens before main
is entered. Here I'm assuming that all your code was compiled in one translation unit: more formally a global variable is initialised immediately before any function defined within the translation unit defining that global variable is encountered. (Although a compiler can optimise this if there are no side effects).
Neither C nor C++ mention the heap or stack in their standards: they are implementation concepts, not language concepts.
So global_var
could be allocated on a heap, but it might be on some kind of stack that is set up before main
is entered.
There's no way of declaring a global variable within a function. A static
variable within a function can mimic much of the behaviour of a global varaible but conceptually, the static
is initialised the first time the function is encountered.