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

时间:2012-06-27 17:48:14

标签: c++ linux gcc gnu

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

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

namespace mynamesp {
   ...
   use mystrings[] here..
   ...
}

但是在Linux上(迄今为止测试过用GCC-4.1.2构建的RHEL5)我很快就出现了分段错误。

$>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)

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

2 个答案:

答案 0 :(得分:5)

您的问题可能会转移到静态初始化顺序fiasco

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

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

进一步阅读: 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

答案 1 :(得分:0)

我遇到了这个问题,事实证明,在我的编译行中,我错过了链接中的最终输出文件。

g++ main.o logger.o timer.o keyboard.o -o main -lSDL -lSDL_image -lSDL_ttf -Wall

应该是

g++ main.o logger.o timer.o keyboard.o drawer.o -o main -lSDL -lSDL_image -lSDL_ttf -Wall

(注意现在包含drawer.o?)

很容易错过,因为我的实际bash编译脚本还有更多行。