强制构建全局对象 [英] Force construction of a global object

查看:50
本文介绍了强制构建全局对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

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.

这篇关于强制构建全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆