Keep an exported function from being deleted by the linker

依然范特西╮ 提交于 2019-12-01 21:08:30

I have seen at least two different approaches to solve similar tasks.

  1. In Qt for example, you can have static plug-ins which need to be "imported" into the main executable by calling a specific macro:

    https://qt-project.org/doc/qt-4.8/qtplugin.html#Q_IMPORT_PLUGIN

    It creates a static instance of a custom class whose constructor calls an initialization function exported from the static plug-in.

  2. The Poco guys force the export of a specific symbol from the static library using an extern "C" declaration on Linux and a pragma on Windows:

    __pragma(comment (linker, "/export:CreateRequestHandler"))

    The linkage to the static library is forced with the same extern "C" declaration on Linux and with a linker pragma on Windows:

    __pragma(comment (linker, "/include:CreateRequestHandler"))

    You can find the details in this blog post.

Can't you provide a .def file to your main executable linker? That file should export the functions in question, which would keep them from being deleted.

I seem to remember that I did something like this long ago.

Problem: On windows, STATIC LIB which contains an OBJ file that has a function marked __decl-spec(dll¬export) but if the same is not used in the EXE, function does not get exported from the EXE. On other platforms also we have the same problem BUT there we have compiler options like --whole-archive / -force_load, do make it work.

Links: Link1 Link2

Only solution that come to my mind is to not create STATIC libs, rather include all code (static LIBS) in the executable then: 1. It works on Windows 2. It works on Linux without --whole-archive 3. It works on Mac OS X without -force_load 4. We also need not worry about if 2 & 3 include the dead code, exe bloat etc.

This is the only solution till the linkers become smart and throw out every unused symbol, except those marked specifically for external consumption i.e. marked to be exported.

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