How can I handle DLL_EXPORT when compiling dll to a static library?

爱⌒轻易说出口 提交于 2020-08-07 09:49:08

问题


I have a project in visual c++ 2010, which contains preprocessor directives in a key header file. Actually, it is the ZMQ source code.

The project is normally configured to be a dll, so the header uses DLL_EXPORT's status (defined/not defined). If the project is used to compile a dll, the header can be used by both the dll project or the client code, thanks to the following setup taken from zmq.h:

#if defined _WIN32
#   if defined DLL_EXPORT
#       define ZMQ_EXPORT __declspec(dllexport)
#   else
#       define ZMQ_EXPORT __declspec(dllimport)
#   endif

However, this does not support the setup where I'm building a static library. Therefore I have to modify to header by hand. Visual studio seems to recognize dll project setup and handle definitions for dll_export accordingly. Is there a symbol that is recognized by visual studio, that corresponds to static library setup? Basically, I'd like to handle static library compilation and usage by extending the method used in the above snippet.


回答1:


I would just introduce a second (optional) macro, something like ZMQ_STATIC:

#if defined(ZMQ_STATIC)
#    define ZMQ_EXPORT
#elif defined(DLL_EXPORT)
#    define ZMQ_EXPORT __declspec(dllexport)
#else
#    define ZMQ_EXPORT __declspec(dllimport)
#endif

Define said macro both when building your library as a static library or when consuming it as a static library.




回答2:


__declspec(dllimport) is completely optional. When you build the DLL, the linker also creates a static import library.

If you compile the client code without __declspec(dllimport), it is compatible with either a fat static library or a static import library. The linker will figure it all out.

So I suggest:

#   if defined DLL_EXPORT
#       define ZMQ_EXPORT __declspec(dllexport)
#   else
#       define ZMQ_EXPORT extern
#   endif

As @vanza points out, you'll need to eliminate any data exports (you can trivially wrap them in accessor functions). You should do that anyway, data exports are fragile.


Note: __declspec(dllimport) results in slightly faster function calls, it's a tradeoff between flexibility to use a static library vs a very small increase in performance calling the DLL.



来源:https://stackoverflow.com/questions/6259022/how-can-i-handle-dll-export-when-compiling-dll-to-a-static-library

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