KHistory
KHistory copied to clipboard
KPlugin: Bug: class's static member var init issue when use gcc
issue commit: f11d9402c1661a586760be9017cb6764d1577f2f
在 C++ 中,全局变量和全局静态变量的初始化时机是不同的。
全局变量的初始化时机是在程序启动时,进入 main 函数之前进行的,初始化顺序与声明顺序有关。也就是说,如果有多个全局变量,它们的初始化顺序取决于它们在源文件中的声明顺序,先声明的先初始化。
而全局静态变量的初始化时机是在它们所在的编译单元被第一次使用时进行的,初始化顺序与声明顺序无关。也就是说,如果有多个全局静态变量,它们的初始化顺序是不确定的,取决于编译器和链接器的实现。
因此,如果在一个编译单元中同时存在全局变量和全局静态变量,并且它们的值相互依赖,那么可能会出现问题。如果全局变量的初始化依赖于全局静态变量的值,而全局静态变量尚未初始化,那么全局变量会被初始化为默认值,从而导致程序错误。
环境
gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Ubuntu 20.04
Breakpoint 1, khistory::KeyHistory::_registerPlugin (plugin=0x555555648008) at src/KeyHistory.cpp:60
60 int KeyHistory::_registerPlugin(KPluginInterface *plugin) {
(gdb)
61 plugin->gameKeyNameTableInit();
(gdb)
62 plugin->gameKeyColorTableInit();
(gdb)
63 _mPluginVec.push_back(plugin);
(gdb)
64 cnt++;
(gdb)
65 DSTRUCT_ASSERT(cnt == _mPluginVec.size());
(gdb)
66 printf("_registerPlugin: %p\n", &_mPluginVec);
(gdb)
_registerPlugin: 0x55555564a010
67 return 0;
(gdb) s
68 }
(gdb)
__static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at src/main.cpp:10
10 KPLUGIN_REGISTER(GamepadBasePluginFighting) // base on GamepadBasePlugin
(gdb)
30 }
(gdb)
0x000055555561da9d in __libc_csu_init ()
(gdb)
Single stepping until exit from function __libc_csu_init,
which has no line number information.
_GLOBAL__sub_I__ZN8khistory10KeyHistory18_mKeyColorMapTableE () at src/KeyHistory.cpp:255
255 }
(gdb)
__static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at src/KeyHistory.cpp:255
255 }
(gdb)
6 dstruct::Vector<ImVec4> KeyHistory::_mKeyColorMapTable;
(gdb)
dstruct::Vector<ImVec4, dstruct::port::Alloc>::Vector (this=0x2)
at third-party/DStruct/core/ds/array/Vector.hpp:12
12 Vector() : _mSize { 0 }, _mCapacity { 0 }, _mC { nullptr } { }
(gdb) n
__static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at src/KeyHistory.cpp:6
6 dstruct::Vector<ImVec4> KeyHistory::_mKeyColorMapTable;
(gdb)
7 dstruct::Vector<KPluginInterface *> KeyHistory::_mPluginVec;
(gdb)