How can I handle DLL_EXPORT when compiling dll to a static library?
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 开发者_JAVA技巧to handle static library compilation and usage by extending the method used in the above snippet.
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.
__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.
精彩评论