静态变量初始化代码永远不会被调用 [英] static variable initialisation code never gets called

查看:145
本文介绍了静态变量初始化代码永远不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用我制作的静态库的应用程序。库中的一个.cpp文件具有静态变量声明,其ctor会在单例函数上调用执行某项操作的函数,例如添加一个字符串。



现在,当我从应用程序中使用该库时,我的单例似乎没有包含应该添加的字符串的任何痕迹。 / p>

我肯定会丢失一些东西,但我不知道什么。.

解决方案

如果静态库中的对象未在应用程序中明确地使用。这样链接器就不会将该对象从库中拉到应用程序中。



静态库和动态库之间有很大的区别。



动态库:

在编译时,不会从动态库中提取任何内容。添加了额外的代码以在运行时显式加载和解析符号。在运行时,将加载整个库,因此将调用对象初始化程序(尽管何时详细说明实现)。



静态库的处理方式非常不同:

当您链接到静态库时,它将静态库中定义的所有未在应用程序中定义的项目拉入应用程序。重复此过程,直到不再有库可以解析的依赖项为止。这样做的副作用是未显式使用的对象/函数不会从库中拉出(因此,不会直接访问未直接访问的全局变量)。


I've got an application that's using a static library I made. One .cpp file in the library has a static variable declaration, whose ctor calls a function on a singleton that does something- e.g. adds a string.

Now when I use that library from the application, my singleton doesn't seem to contain any traces of the string that was supposed to be added.

I'm definitely missing something but I don't know what..

解决方案

If you have an object in a static library that is not EXPLICITLY used in the application. Then the linker will not pull that object from the lib into the application.

There is a big difference between static and dynamic libraries.

Dynamic Library:
At compile time nothing is pulled from the dynamic library. Extra code is added to explicitly load and resolve the symbols at run-time. At run time the whole library is loaded and thus object initializers are called (though when is implementation detail).

Static libraries are handled very differently:
When you link against a static library it pulls all the items that are not defined in application that are defined in the library into the application. This is repeated until there are no more dependencies that the library can resolve. The side effect of this is that objects/functions not explicitly used are not pulled form the library (thus global variables that are not directly accessed will not be pulled).

这篇关于静态变量初始化代码永远不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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