Search code examples
c++cmemorycompilationhardware

How does compilation reserve space in stack?


I don't have much knowledge in computers, so my questions are quite naive.

I learned that compilation of a C code reserves specific memory space in stack in the main memory during compilation.

Then,

  1. Why does an executable work when it is compiled in one computer copied over to another computer?

  2. If compilation reserve specific memory location of RAM, then are the number of executables (or compilation) limited by size of the RAM?

  3. If compilation reserves space in RAM, why does an executable occupy a lot more disk space than pre-compilation .C text file?

Thank you


Solution

    1. The stack is not reserved by the compiler in the compilation time. It is reserved in a sense that the compiler is inserting specific commands and directives into the executable, for the stack to be reserved when the executable is being loaded/run

    2. No. See above. The RAM is not reserved (that is made unavailable to other executables) at a time of compilation. It is reserved when the executable is being loaded/executed.

    3. This is not necessarily true. In many case the executable is smaller than the code. But it can depend on many factors, such as how the code is written, the executable format, metadata included in it and memory layout. Sometimes the executable will contain whole zero-filled sections, which can be defined by a single line in the code.

    In general, a compiler (in conjunction with linker whatsoever, if we want to be pedantic) has only one "simple" job - to take input files (code) and generate output file(s) - the executable. That is - it is creating files, that are only occupying space in the file system. Other things can happen only when the environment (OS) is loading and doing something (loading, executing) with them.