static memory allocation

For a static object declared in a file which is going to be separately compiled-
(i) what exactly happens at compile time.
- Does size of the .o file increases with the increase in the size of the static object.?
- Has the memory layout of the object already been done and the contents are initialized with the values (which have been provided at the compile time.) ?
- OR only the memory layout decided and content will be initialized with the given compile time constant later at run time.?
(ii) what happens at the load time.
If there are 10 statics in 10 different files, then the memory allocation for these 10 objects is done at the time when program is loaded (starts) before main?
(iii) what happens at run time.
In case the static variable is declared in a CPP file ( which is in some shared library). That library is not loaded unless a function from that library is called, so the static variable will not be constructed and initialized unless the control goes to any one function of the file where the static object is declared??

thanks.
(i) what exactly happens at compile time.

the size of each static is calculated and stored int the object file
for constant-initialized statics, the initial value is calculated and stored in the object file

(ii) what happens at the load time.

The .bss segment is allocated and zero-filled, big enough to fit all non-const statics
For constant-initialized non-const statics, their initial values are memcpy'd into .bss
For other non-trivial file scope statics, constructor arguments or other initializing expressions are executed, and then constructors are called
main() is called

If there are 10 statics in 10 different files, then the memory allocation for these 10 objects is done at the time when program is loaded (starts) before main?

Yes, the size of the program's bss will be big enough for those 10 statics.

some shared library). That library is not loaded unless a function from that library is called, so the static variable will not be constructed and initialized unless the control goes to any one function of the file where the static object is declared??

Sure, if that's your dynamic linker's strategy. A shared library has its own bss, which the dynamic linker will map, zero-fill, and call constructors on, sooner or later (it's not defined when). Normally it all happens on startup unless you dlopen() by hand.
Last edited on
Topic archived. No new replies allowed.