-1

I still can't quite grasp the concept of how the compiler stores automatic (local) variables before runtime.

I can understand that the compiler puts static variables in the data or bss segments. Auto variables on the other hand get placed on the stack, but not until runtime when a function is called. So where are they stored before the program executes?

My guess is that the compiler just needs to know the size of the local variables, as placeholders, but can we see this information in the object files?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Engineer999
  • 3,683
  • 6
  • 33
  • 71
  • 3
    They don't have to be "stored", they do not exist until the scope is entered. Some space is reserved on the stack when entering the scope, and reclaimed when exiting the scope. – spectras Jul 22 '17 at 21:58

1 Answers1

1

Variables declared outside of functions are either global/namespace-scoped or class members. Automatic variables are those declared within functions. Automatic variables do not exist until they are encountered in a function's execution at runtime.

As such, they are not stored anywhere before the executable is executed.

With typical compilers, when compiling a function, and the compiler encounters a local variable declaration, it emits instructions to reserve a quantity of stack space sufficient for that variable's size and alignment. This is usually done by increment a particular register by a static amount. The compiler then emits the code to initialize the object within that storage.

When that variable goes out of scope, after calling the appropriate destructors, the compiler issues instructions to decrement the stack register. That way, later code can reuse that stack space for other local variables.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982