考虑一个使用导入库 logging.lib 的 Windows 程序,这样 logging.dll 将在运行时自动加载/卸载。
另外,考虑主程序的翻译单元之一定义类类型的全局变量,如下所示:
struct InitGuard
{
InitGuard()
{
logging::initialize();
}
~InitGuard()
{
logging::deinitialize();
}
};
InitGuard g_initGuard;
除了更好的方法是在函数 main
中实例化 InitGuard
之外:
- 是否保证 logging.dll 在调用
InitGuard
的 c'tor 时已经加载? - 更重要的是,是否保证 logging.dll 在
InitGuard
的驱动程序返回之前不会被卸载?
最佳答案
Is it guaranteed that logging.dll will already be loaded when the c'tor of
InitGuard
is invoked?
是的。在任何 EXE 代码开始运行之前,所有对static 链接 DLL 的引用都由 OS Loader 解析。
Even more importantly, is it guaranteed that logging.dll will not yet be unloaded before the d'tor of
InitGuard
has returned?
是的。在 EXE 代码运行完毕之前,操作系统不会释放静态链接的 DLL。
关于c++ - 在全局变量的初始化/取消初始化中使用隐式加载的 DLL 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57782516/