Force construction of a global object(强制构造一个全局对象)
问题描述
代码如下:
struct S
{
S()
{
__debugbreak();
}
};
static const S g_s;
显然,我希望在启动时运行一些代码.
Obviously, I want some code to run at startup.
这仅适用于某些源文件,其符号被外部代码引用.对于静态库中没有从外部引用任何符号的源文件,看起来编译器或链接器会删除完整的编译单元,因此不会构造全局对象.
This only works for some source files, that have symbols referenced by outside code. For source files in a static library that don’t have any symbols referenced from outside, looks like the compiler or linker drop the complete compilation unit, so the global object is not constructed.
有没有办法强制构造静态对象,或者强制在启动时运行代码?
Is there a way to force construction of static objects, or otherwise force running of the code at startup?
我已经仔细检查了这些源文件的编译设置,它们是相同的,并且它们在同一个静态库项目中.
I’ve double checked compilation settings for these source files, they are identical, and they are in the same static library project.
静态库由 DLL 使用.全局对象应在调用 DLL_PROCESS_ATTACH 之前构建.
The static library is used by a DLL. Global objects are expected to be constructed before DLL_PROCESS_ATTACH call.
推荐答案
您需要使用链接器选项链接此库中的所有内容",例如
You will need to link "everything" from this library using linker options such as
-Wl--whole-archive -lmylib -Wl--no-whole-archive (gcc)
或
/INCLUDE symbol (vc)
或
/WHOLEARCHIVE:mylib (vc)
但是,在程序启动/dll 加载期间依赖动态初始化阶段和/或对全局对象的状态做出假设会使您的程序注定失败.所以你应该考虑显式初始化.
However relying on dynamic initialization stage and / or making assumptions about state of global objects during program startup / dll loading makes your program doomed. So you should consider explicit initialization instead.
这篇关于强制构造一个全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:强制构造一个全局对象
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07