Linking a shared library against a static library: must the static library be compiled differently than if an application were linking it?

浪尽此生 提交于 2019-11-28 17:30:31

You do not have to use PIC code in shared objects (as you have discovered you can use the -mimpure-text option to allow that).

That said, non-PIC code in shared objects are more heavyweight. With PIC code, the text pages in memory are just direct memory mappings of the text pages on disk. This means that if multiple processes are using the shared object, they can share the memory page.

But if you do not have PIC code, when the runtime linker loads the shared object, it will have to apply fixups to the text pages. This means that every processes that uses the shared object will have it's own unique version of any text page that has a fixup on it (even if the shared object is loaded at the same address as copy-on-write only notices that the page was modified and not that it was modified in the same way).

To me, the important issue is whether you will simultaneously have multiple processes running that each load the shared object. If you do, it is definitely worth making sure all the code within the SO is PIC.

But if that is not the case and only a single process has the shared object loaded, it's not nearly as critical.

I do the following in the link stage for the shared object library version of a static library: g++ -shared -o libshared.so -Wl,--whole-archive -fPIC -lstatic -Wl,--no-whole-archive. Since --whole-archive links every object in a (list of) static libs (of the form libstatic.a) I believe preceding that (list) with -fPIC is all the OP need do.

As an alternative approach, ship two libraries: your shared one and the static you're linking against alongside. They should link into the final executable correctly.

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