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.
这篇关于强制构造一个全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:强制构造一个全局对象


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01