Linux 下 so 共享库的 dlclose 卸载问题

Saleayas Saleayas 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
在 Linux 下创建一个共享库,在该库中使用
void Init(void) __attribute__((constructor));
void Final(void) __attribute__((destructor));
标识一对函数,来显示模块的加载和卸载。
同时创建一个测试的 Console 程序,测试加载和卸载。
简单的情况下,当dlopen 的时候,Init 函数被调用, dlclose 的时候,Final 函数被调用。

但是,当我在共享库中添加一个类。并且这个类中添加一个成员函数(不管是否是静态的)。
如果这个函数使用了一个静态变量(不是类的静态变量,是函数的静态变量)。
同时导出函数的呼叫路径上使用了这个函数。
那么此时 当 dlclose 的时候, Final 函数没有被调用。而是等到整个 Console 程序退出时, Final 函数才被调用。

共享库的 main.cpp 代码
class CMath
{
public:
void A()
{
int const es[] = { 1, 2 };
int index = 0;
printf("%d", es[index]);
}

static void B()
{
static int const es[] = { 1, 2 };
int index = 0;
printf("%d", es[index]);
}

// static void C()
// {
// int const index = 0;
// printf("%d", _es[index]);
// }
//
// static int const _es[2];
};

//int const CMath::_es[2] = {1, 2};

void Export()
{
//CMath _;
//_.A();
CMath::B();
//CMath::C();
}
void Export() __attribute__((visibility("default")));

static void _Init(void)
{
printf("module loaded.\n");
}
static void _Final(void)
{
printf("module unloaded.\n");
}

void _Init(void) __attribute__((constructor));
void _Final(void) __attribute__((destructor));


// 测试代码 main.c 代码。
int main()
{
void *handle;
printf("dlopen ...\n");
handle = dlopen("libShare.so", RTLD_LAZY);
printf("dlopened.\n");
assert(handle);

printf("dlclose ...\n");
dlclose(handle);
printf("dlclosed.\n");

return getchar();
}


请教一下,这是什么问题。
还有就是怎样解决这个问题。
我需要在成员函数中定义静态变量。
...全文

相关推荐

评论 12
收藏 已收藏
分享
返回顶部
Saleayas
C++ 语言 65,214 成员 250,514 内容