简体   繁体   中英

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

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.

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM