Research on the initialization sequence of global and static variables in C ++
I encountered a very difficult problem during programming, that is, static variable initialization. In some cases, a global (static) variable depends on another global (static) variable. For example, in the factory mode, register a creator using implicit registration, but it depends on the initialization of the factory. If the factory is not initialized, the registration will fail.ProgramAn unknown exception is thrown. These are completed before C ++ enters the main function. Before entering the main function, crt0dat. c assigns initial values to these global or static variables. The question is, in general, what is the initialization order? I was also confused at the beginning, but after I asked questions online and debugged many times, I finally learned the secrets.
My environment is vs2005, that is, the VC ++ 8 compiler is used. During compilation, didn't we see that the output column shows the compiled source file? When compiling source files, the compiler records global variables, Global static variables, and static variables. Form a table in the order of compilation, and initialize the table before the main () function starts. Therefore, sometimes we can see that a window pops up when some programs are opened, such as 360, it performs a lot of security checks before initialization.
let's talk more about it here. For example, if I have a factory g_factory Global Object and blockcreator g_blockcreator object, because the global variables cannot be defined in the header file (if there are multiple source files, the nkl2005 error will be reported ), we add the extern keyword to the factory in the header file to postpone its definition to the source file. Next, how can we ensure that g_blockcreator is initialized after g_factory.
assume that the g_factory definition is placed in the factory. in CPP, g_blockcreator is defined in block. in CPP, block is compiled according to the vs2005 alphabet. CPP will be compiled first, factory. CPP is compiled later, so g_blockcreator will be initialized before g_factory, which is not allowed. Therefore, we can change factory. cpp to $ factory. cpp (or any letter with the ASCII order before B), close vs2005, and compile it to achieve the effect. Remember to close vs2005 after changing the file name, otherwise it will be compiled in the order of B-F compilation, although the source file starting with F does not exist. After it is re-opened, it will be compiled in the order of $-B. You don't have to worry about the initialization order.