跨c ++翻译单元的初始化

时间:2012-07-12 20:51:16

标签: c++ gcc g++

或者我有两个文件,每个文件都有一个全局初始化。一个取决于另一个。

简化示例:

file1.h:

#include <string>
extern const std::string PREFIX;

file1.cpp:

#include "file1.h"
const std::string PREFIX  = "prefix,";

file2.cpp:

#include "file1.h"
std::string MSG = PREFIX + "body";
int main(){}

我按原样编译它们:

/usr/local/bin/g++-4.6.2 -c -Wall -g -o file1.o file1.cpp
/usr/local/bin/g++-4.6.2 -c -Wall -g -o file2.o file2.cpp
/usr/local/bin/g++-4.6.2 -Wall -g  -o example file1.o file2.o

当我运行它时,会出现段错误。 gdb trace:

Starting program: example

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b7ae0b in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) ()
  from /usr/local/lib/gcc/x86_64-unknown-linux-gnu/4.6.2/libstdc++.so.6 
(gdb) bt
#0  0x00007ffff7b7ae0b in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) ()
   from /usr/local/lib/gcc/x86_64-unknown-linux-gnu/4.6.2/libstdc++.so.6
#1  0x00000000004009b5 in std::operator+<char, std::char_traits<char>, std::allocator<char> > (__lhs=Traceback (most recent call last):
   File "/usr/local/lib/gcc/x86_64-unknown-linux-gnu/4.6.2/../../../../share/gcc-4.6.2/python/libstdcxx/v6/printers.py", line 587, in to_string
     return ptr.lazy_string (length = len)
RuntimeError: Cannot access memory at address 0xffffffffffffffe8
, __rhs=0x400af0 "body") at /usr/local/lib/gcc/x86_64-unknown-linux-gnu/4.6.2/include/c++/bits/basic_string.h:2346
#2  0x000000000040095f in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at file2.cpp:3
#3  0x000000000040098b in _GLOBAL__sub_I_MSG () at file2.cpp:6
#4  0x0000000000400ab6 in __do_global_ctors_aux ()
#5  0x00000000004006e3 in _init ()
#6  0x00007ffff7ffa5a0 in ?? ()
#7  0x0000000000400a45 in __libc_csu_init ()
#8  0x00007ffff72dcbe0 in __libc_start_main () from /lib/libc.so.6
#9  0x00000000004007c9 in _start ()

无论如何都要做我想做的事情(请记住这是一个过于简化的例子)?或者我受编译器/链接器选择的初始化顺序的支配?

3 个答案:

答案 0 :(得分:5)

您需要在其他字符串之前使前缀字符串存在。一种方法是将其更改为C字符串

// header
#include <string>
extern const char * const PREFIX;

// .cpp file
const char * const PREFIX = "prefix,";

另一种方法是从函数返回前缀,并使用PREFIX()之前使用的PREFIX

// header
inline const string& PREFIX() { 
  static const string value = "prefix,";
  return value;
}

最后,只是一个提示:所有大写字母的名称仅用于大多数编码约定中的宏,因此我会避免使用变量和函数的名称。

答案 1 :(得分:0)

我想这是因为代码尝试以错误的顺序初始化全局变量。有一个SO question about initialisation order,它的答案应该证明是有用的。

答案 2 :(得分:0)

这显然不是一个可移植的解决方案,但对于 gcc ,您可以使用function attributes - __attribute__语法。即__init_priority__ (priority)属性。初始化优先级跨越翻译单元。 link