动态库和主程序中的静态类变量 [英] Static Class Variables in Dynamic Library and Main Program

查看:250
本文介绍了动态库和主程序中的静态类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个包含静态stl容器类的类'A'的项目。这个类包含在我的主程序和.so文件中。该类使用默认(隐式,未声明)构造函数/析构函数。主程序使用dlopen()加载.so文件,并在其析构函数中调用dlclose()。当glibc调用静态类成员变量的析构函数时,程序在主退出之后崩溃。问题似乎是,当dlclose()被调用时,静态变量的析构函数被调用,然后当main exits()glibc也调用析构函数,导致双重释放。

I am working on a project that has a class 'A' that contains a static stl container class. This class is included in both my main program and a .so file. The class uses the default(implicit, not declared) constructor/destructor. The main program loads the .so file using dlopen() and in its destructor, calls dlclose(). The program crashes after main exits when glibc calls the destructor for the static class member variable. The problem appears to be that when dlclose() is called, the destructor for the static variable is called, then when main exits() glibc also calls the destructor, resulting in a double free.

我有两个问题,即:

1)在这种特殊情况下,为什么没有静态变量的两个副本(是的,我知道听起来有点荒谬,但由于两个主程序和.so文件有单独编译的'A',它们应该不是一个?)

2)有没有办法解决这个问题,而不重写类'A'不包含静态成员变量?

I have 2 questions, namely:
1) In this particular case, why are there not two copies of the static variable(yes i know that sounds somewhat ridiculous, but since both the main program and .so file have a separately compiled 'A', shouldn't they each have one?)
2) Is there any way to resolve this issue without re-writing class 'A' to not contain static member variables?

推荐答案

此问题已在我发布的另一个问题中解决。基本上,静态变量确实有两个副本 - 一个在主程序中,另一个在共享库中,但运行时链接器将两个副本都解析为主程序副本。有关详情,请参阅此问题:

This question has been resolved in another question I posted. Basically there were indeed two copies of the static variable -- one in the main program and one in the shared library, but the runtime linker was resolving both copies to the main programs copy. See this question for more information:

http://stackoverflow.com/questions/2631918/main-program-and-shared-library-initializes-same-static-variable-in-static-init

这篇关于动态库和主程序中的静态类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆