Purpose of static_initialization_and_destruction and _GLOBAL__sub_I_main function in the assembly code for a C++ code?

房东的猫 提交于 2019-12-05 14:38:52

Both functions are used by gcc in C++ for any instantiated classes with static storage duration that need to be constructed before main e.g.

class A {
    A();
    ~A();
    ... 
};

A a;

// "a" will need to be constructed before main
int main()
{
    return a.Foo();
}
// "a" will need to be destructed after main

The generated _Z41__static_initialization_and_destruction_0ii function (demangled __static_initialization_and_destruction_0(int, int)) serves 2 purposes:

  • Call any constructors of classes with static storage duration in the preprocessed/compiled C++ source file (when required)
  • Register destructors of classes with static storage duration in the preprocessed/compiled C++ source file (when required) as exit functions via atexit.

_GLOBAL__sub_I_main is a simple wrapper function around it, who's function-pointer is added to the .init_array section. When compiling multiple source files, each individual object file will add initialization functions to the .init_array and all of those functions will be called before main is called.

While this may not be immediately obvious your code contains an instance with static storage duration. The <iostream> header file declares std::ios_base::Init which needs to be constructed as early as possible to make it safe to access the standard I/O streams in the constructors and destructors of static objects.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!