强制构造一个全局对象

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.

这篇关于强制构造一个全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:强制构造一个全局对象

基础教程推荐