3

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

4

2 回答 2

7

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

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

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

进一步阅读: 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
于 2015-12-22T08:36:58.050 回答
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 编译脚本有更多行。

于 2013-02-24T18:02:08.687 回答