gpt4 book ai didi

C++、全局变量和动态共享库

转载 作者:太空宇宙 更新时间:2023-11-04 09:39:32 24 4
gpt4 key购买 nike

我知道全局变量很糟糕,但即使是函数的局部静态变量也似乎很糟糕。

我注意到在 Linux 上,共享对象(动态库)中的全局变量和静态变量在您第一次使用 dlopen 时被初始化。但是当您 dlclose,然后再次 dlopen 时,它不会第二次初始化全局变量或静态变量。

我使用 RTLD_NOLOAD 和 dlopen 来测试 dlclose 是否真的删除了库,它说它删除了,所以这不是引用计数问题。

这与 Windows 不同: http://msdn.microsoft.com/en-us/library/988ye33t.aspx我已经测试过并且确实似乎重新初始化了静态。

这是真的吗,还是我只是把事情搞砸了?

如果这是真的,这不会使任何类型的静态变量变得危险/无用吗?

最佳答案

But when you dlclose, and then dlopen again, it doesn't initialise globals or statics the second time.

这很可能发生,因为该库实际上dlclose 上卸载。

来自 man dlclose

The function dlclose() decrements the reference count on the dynamic library
handle handle. If the reference count drops to zero and no other loaded
libraries use symbols in it, then the dynamic library is unloaded.

很可能您不满足“没有其他加载的库在其中使用符号”部分。

您可以使用 LD_DEBUG=symbols,bindings 运行二进制文件并观察如下消息:

    binding file XXX to libYYY.so: normal symbol `ZZZ'

如果您将 libYYY.so 中的任何符号绑定(bind)到一个卸载的文件,则 libYYY.so 无法卸载在 dlclose 上。

关于C++、全局变量和动态共享库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22873786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com