Linking to static C++ library on Mac OS X: global object constructor from library is not called

自闭症网瘾萝莉.ら 提交于 2021-01-29 13:53:11

问题


My static C++ library contains some global object with a constructor. Test program is built with Apple's gcc 4.2.1, and upon run one can see the object is zero-initialized, but constructor is not called. The same is true for any static class member variables.

It is possible to correct this issue by providing -force_load option to ld, but this way is not good due to big executable size. I tried to reference functions from the file, where global object is defined, but it gave no effect.

When building the same code under Linux (gcc 4.5.1) there are no such issues.


回答1:


This is because when linking a binary to an archive (.a) the linker only pulls in symbols from the archive that are unresolved in the binary. That is, if the binary does not refer to that global (or static) object from the archive, that object's symbol and its initialization code won't be linked in.

It is a common problem with archives and unreferenced global objects. The common solution is to refer to that object from the binary somehow (e.g. take its sizeof). Or provide an initialization function for that library that does what that global object's constructor is supposed to do and make your binary call that function.



来源:https://stackoverflow.com/questions/6579668/linking-to-static-c-library-on-mac-os-x-global-object-constructor-from-librar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!