海湾合作委员会__static_initialization_and_destruction_0(__initializ

GCC __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535)

本文关键字:and destruction initializ initialization static 委员会      更新时间:2023-10-16

根据帖子,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 行基本上指向我的字符串数组定义的末尾。我看到其他一些人收到此错误;但没有明显的修复。一如既往地欣赏任何想法/想法/更正。谢谢!

您的问题可能与静态初始化顺序的惨败有关。

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

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

延伸阅读: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

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

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

(注意到现在包含的抽屉.o吗?

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