根据这篇文章,Standalone functions/data in C++,我继续将我的“公共数据”放在一个匿名名称空间中,如下所示,一切都在VS2005/2008/2010上的视窗(Vista64位)上工作得很好
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行基本上指向我的字符串数组定义的末尾。我见过其他一些人得到了这个错误;但没有明显的修复。一如既往地感谢任何想法/想法/修正。谢谢!
发布于 2015-12-22 16:36:58
您的问题可能与静态初始化顺序失败有关。
当您使用另一个静态变量初始化一个静态变量时,就会发生这种情况。当后一个变量尚未初始化时,第一个变量使用一个未初始化的变量进行初始化。
根本原因是初始化静态变量的顺序未定义。
进一步阅读: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发布于 2013-02-25 02:02:09
我遇到了这个问题,结果发现在我的编译行中,我错过了链接中的最终输出文件。
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编译脚本有更多的行。
https://stackoverflow.com/questions/11232123
复制相似问题