GCC __static_initialization_and_destruction_0(__ inititize_p = 1,__ priority = 65535)

squ*_*boo 2 c++ linux gcc gnu

根据帖子,C++中的独立函数/数据,我继续将我的"公共数据"放在匿名命名空间中,如下所示,VS 2005/2008/2010上的所有内容在Windows(Vista 64位)上运行良好

namespace {
  ...
  static std::string mystrings[] = {
     str1,
     str2,
     ...,
     strN
  };
  ...
}

namespace mynamesp {
   ...
   use mystrings[] here..
   ...
}
Run Code Online (Sandbox Code Playgroud)

但是在Linux上(到目前为止测试的RHEL5使用GCC-4.1.2构建)我很快就出现了分段错误.

$>myprog 
Segmentation fault
$>gdb myprog 
GNU gdb Fedora (6.8-27.el5)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu"...
(gdb) r
Starting program: <path/to>/myprog 
[Thread debugging using libthread_db enabled]
[New Thread 0x2b8901a9da60 (LWP 32710)]

Program received signal SIGSEGV, Segmentation fault.
0x0000003e4ce9c928 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string ()
   from /usr/lib64/libstdc++.so.6
(gdb) bt
#0  0x0000003e4ce9c928 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string ()
   from /usr/lib64/libstdc++.so.6
#1  0x00002b88ffde482b in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535)
    at <path/to>/mysource.cpp:140
#2  0x00002b88ffde4d65 in global constructors keyed to _ZN91_GLOBAL__N__underscore_separated_path_to_mysource.cpp_00000000_6994A7DA2_1E () at <path/to>/mysource.cpp:12139
#3  0x00002b890011a296 in __do_global_ctors_aux ()
   from <path/to/libs>/debug/libmylibd.so
#4  0x00002b88ffcd7f33 in _init () from <path/to/libs>/debug/libmylibd.so
#5  0x00002b8901672e40 in ?? ()
#6  0x000000326940d22b in call_init () from /lib64/ld-linux-x86-64.so.2
#7  0x000000326940d335 in _dl_init_internal () from /lib64/ld-linux-x86-64.so.2
#8  0x0000003269400aaa in _dl_start_user () from /lib64/ld-linux-x86-64.so.2
#9  0x0000000000000001 in ?? ()
#10 0x0000000000000000 in ?? ()
(gdb)
Run Code Online (Sandbox Code Playgroud)

回溯调用堆栈项#1中的第140行基本上指向我的字符串定义数组的结尾.我见过其他人得到这个错误; 但没有明显的修复.一如既往地欣赏任何想法/想法/更正.谢谢!

Man*_*ork 5

你的问题可以归结为静态初始化命令惨败.

使用另一个静态变量初始化静态变量时会发生这种情况.当后一个尚未初始化时,第一个是使用非初始化变量进行初始化.

根本原因是初始化静态变量的顺序是未定义的.

进一步阅读:https: //isocpp.org/wiki/faq/ctors#static-init-order

一个典型的解决方法是将静态变量包装在函数中.例:

T& GetStaticA() {
  T static_var_A; // <--initialization here
  return A;
}

T static_var_B = GetStaticA(); // <-- static_var_A is guaranteed to be initialized
Run Code Online (Sandbox Code Playgroud)