共享库中 __attribute__((构造函数)) 的全局/静态变量初始化问题
Global/Static variables initialization issue with __attribute__((constructor)) in shared library
我在共享库中使用__attribute__((constructor))
初始化全局/静态变量时遇到了一个问题,某些变量似乎被初始化了两次。
以下是代码片段:
共享.cpp
struct MyStruct
{
MyStruct(int s = 1)
: s(s) {
printf("%s, this: %p, s=%dn", __func__, this, s);
}
~MyStruct() {
printf("%s, this: %p, s=%dn", __func__, this, s);
}
int s;
};
MyStruct* s1 = nullptr;
std::unique_ptr<MyStruct> s2 = nullptr;
std::unique_ptr<MyStruct> s3;
MyStruct s4;
void onLoad() __attribute__((constructor));
void onLoad()
{
s1 = new MyStruct;
s2 = std::make_unique<MyStruct>();
s3 = std::make_unique<MyStruct>();
s4 = MyStruct(2);
printf("&s1: %p, &s2: %p, &s3: %pn", &s1, &s2, &s3);
printf("s1: %p, s2: %p, s3: %pn", s1, s2.get(), s3.get());
printf("s4: %p, s4.s: %dn", &s4, s4.s);
}
extern "C" void foo()
{
printf("&s1: %p, &s2: %p, &s3: %pn", &s1, &s2, &s3);
printf("s1: %p, s2: %p, s3: %pn", s1, s2.get(), s3.get());
printf("s4: %p, s4.s: %dn", &s4, s4.s);
}
主.cpp
#include <cstdio>
#include <dlfcn.h>
using Foo = void(*)(void);
int main()
{
printf("Calling dlopen...n");
void* h = dlopen("./libshared.so", RTLD_NOW | RTLD_GLOBAL);
Foo f = reinterpret_cast<Foo>(dlsym(h, "foo"));
printf("nCalling foo()...n");
f();
return 0;
}
编译方式
$ g++ -fPIC -shared -std=c++14 shared.cpp -o libshared.so
$ g++ -std=c++14 -o main main.cpp -ldl
输出:
Calling dlopen...
MyStruct, this: 0x121b200, s=1
MyStruct, this: 0x121b220, s=1
MyStruct, this: 0x121b240, s=1
MyStruct, this: 0x7ffc19736910, s=2
~MyStruct, this: 0x7ffc19736910, s=2
&s1: 0x7fb1fe487190, &s2: 0x7fb1fe487198, &s3: 0x7fb1fe4871a0
s1: 0x121b200, s2: 0x121b220, s3: 0x121b240
s4: 0x7fb1fe4871a8, s4.s: 2
MyStruct, this: 0x7fb1fe4871a8, s=1
Calling foo()...
&s1: 0x7fb1fe487190, &s2: 0x7fb1fe487198, &s3: 0x7fb1fe4871a0
s1: 0x121b200, s2: (nil), s3: 0x121b240
s4: 0x7fb1fe4871a8, s4.s: 1
~MyStruct, this: 0x7fb1fe4871a8, s=1
~MyStruct, this: 0x121b240, s=1
s1
和s3
的值是预期的。
但s2
和s4
表现得很奇怪。
s2.get()
应该是0x121b220
,但在foo()
中它变成了nullptr
;s4
的值在onLoad()
中被打印为s4.s: 2
,但之后它的构造函数被调用,默认值为s=1
,那么在foo()
它的值是s=1
。
将变量放在匿名命名空间中具有相同的结果。
s2
和s4
有什么问题?
我的操作系统:Ubuntu 16.04.2,GCC:5.4.0
根据对此 GCC 错误报告和此后续文档补丁的讨论,您看到的似乎是 GCC 中未指定的行为(不是错误)。
但是,未指定具有静态存储持续时间的C++对象的构造函数和用属性
constructor
修饰的函数的顺序。在混合声明中,属性init_priority
可用于强制实施特定排序。
在这种情况下,似乎勉强避免了段错误,因为分配给未初始化的std::unique_ptr
可能会导致为未初始化的指针成员调用delete
。 根据C++规范,GCC 的未指定行为转换为未定义的行为(在此特定情况下),因为从未初始化的变量读取是未定义的行为(未初始化的unsigned char
除外)。
无论如何,要纠正此问题,您确实需要使用__attribute((init_priority))
在构造函数之前对静态声明的对象进行排序初始化。
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 模板基类中的静态变量
- 类和静态变量
- 不同作用域中的静态变量和全局变量
- 静态变量声明和定义
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 在类中继承静态变量?
- "local scope"中的 C++ 初始化静态变量
- 使用静态变量的递归调用的不同输出
- 复制文件流C++静态变量
- 跨模板化函数编译的静态变量
- C++编译器是否优化了顺序静态变量读取?
- C++,每个循环初始化一个新的静态变量
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- 程序如何知道静态变量是否需要初始化?
- 类外的静态变量实例化
- 无法解析静态变量
- 函数局部静态变量:从性能角度来看的优点/缺点
- 访问从 CPP 文件到其他头文件的静态变量