Static initialization - my understanding

zhaozj2021-02-11  141

First of all, it is clear that all initialization is done at runtime.

0) INT G; 1) int global = rand (); 2) const INT CI = 5;

3) struct test4) {5) TEST (): i_ (10) {} 6) I_; 7)};

8) TEST GLOBAL_OBJECT;

9) Void fun () 10) {11) int local; 12) int Local2 = 100; 13)}

14) INT MAIN () 15) {16) Fun (); 17) static int Si; 18) Return 0; 19)}

11 rows of local is the program running to the FUN () function, allocated in the stack, the same, but it has been initialized to 100, value. Such initialization can be regarded as "dynamic initialization", only to run to the FUN () function, will initialize, and for all Global Object (include Variable Variable) in the program, they must initialize as long as the program begins to run. Ok, this process you don't know, you just know, whether in which place in your program, you can use them, never have access viocation. :), that is called "static initialization".

This data is placed in three sections of the .exe file. .DATA (I have initialized data), .rdata (read-only initialized data), .bss (no initialized data), Note: Ordinary temporary variables do not appear in the EXE file. Since C will initialize all you do not initialize data as 0, such as 0 lines above, it is only involved in .data, .rdata two sections, BSS for C.

How to achieve static initialization, this problem is too complicated, I can't make a deep explanation, as will be described below.

__sys_main () {__sti (); main () __STD ();

__sti () is responsible for performing static initialization, (0, 1, 2 lines in this case) and then call the main (), and final __std () call DTOR. This is just a thinking, does not mean that the compiler is implemented.

In the above example, 0 row g is placed in 0 values. Data, 1 line Global is also placed in 0 values ​​(cannot be evaluated at compile time). Data, 2 lines CI is set to. RDATA, 8 lines Global_Object It is placed in 0 values. Data, truly need to appear in __sti () CI and Test :: Test (), and other in the program run, the exe file image is already the correct value.

It can be seen that there is no need to static initialization in C, or only a constant (compile time evaluation) (this is the requirements of C), or no initialization.

(In order to improve efficiency, Standard C requires that Static Object starts when its function is running, it seems to be "dynamic", :) but it is released in __std ()).

转载请注明原文地址:https://www.9cbs.com/read-5507.html

New Post(0)