全局字符串在共享库中取消设置

Global string unsets itself in shared library

共享库中的全局变量如何自行取消设置?我正在试验一个非常简单的库,我注意到全局 std::string 不保持它的值。这是我的完整代码:

在libfoo.cxx中:

#include <string>
#include <iostream>

using namespace std;

static string name;

__attribute__((constructor))
static void init() {
  ios_base::Init init_ios;

  name = "LIBFOO";
  cout << "init name: " << name << endl;
}

extern "C" const char *get_name() {
  return name.c_str();
}

在libfoo.h中:

#ifndef LIBFOO_H
#define LIBFOO_H

extern "C" const char *get_name();

#endif

在test.cxx中:

#include <iostream>
#include "libfoo.h"

int main() {
  std::cout << "main name: " << get_name() << std::endl;
}

建造:

g++ -o libfoo.so -shared -fPIC libfoo.cxx
g++ -o test test.c -L. -lfoo

运行:

LD_LIBRARY_PATH=$PWD ./test

输出:

init name: LIBFOO
main name: 

name的值去哪儿了?变量如何取消自身设置?

你在这里踏上了泥泞的土地,因为不同类型的构造函数(C++ 构造函数与属性构造函数)的顺序没有很好地定义,并且可能跨编译器(参见 c-static-initialization-vs-attribute-constructor )。所以我的猜测是首先你分配给 name 然后默认构造函数运行,将它重置为空字符串。您可以通过逐步执行 gdb 下的初始化代码来验证这一点。