由于我在动态加载的库中观察到了全局变量的一些奇怪行为,因此我编写了以下测试.
首先,我们需要一个静态链接的库:标题 test.hpp
#ifndef __BASE_HPP
#define __BASE_HPP
#include <iostream>
class test {
private:
int value;
public:
test(int value) : value(value) {
std::cout << "test::test(int) : value = " << value << std::endl;
}
~test() {
std::cout << "test::~test() : value = " << value << std::endl;
}
int get_value() const { return value; }
void set_value(int new_value) { value = new_value; }
};
extern test global_test;
#endif // __BASE_HPP
Run Code Online (Sandbox Code Playgroud)
和来源 test.cpp
#include "base.hpp"
test global_test = test(1);
Run Code Online (Sandbox Code Playgroud)
然后我写了一个动态加载的库: library.cpp
#include …Run Code Online (Sandbox Code Playgroud)