Creating shared and static libraries using g++ (under Windows)
How do I create static and dynamic libraries for Windows using g++?
I've found a few commands for Linux for creating .so
files and I've tried to apply them on a Windows shell, but they build .dll
files that my applications fail to link with at runtime.
I've only managed to build .dll
files using Visual C++ but I would like to build them manually on the command line, preferably using g++
. I would also like to know how to build static libraries too for Windows.
You need to prefix with the attribute :
__declspec(dllexport)...
all the features you want to expose.
See this.
Example for a C function:
__declspec(dllexport) int __cdecl Add(int a, int b)
{
return (a + b);
}
This can be simplified using MACROS
: everything is explained on this helpful page.
For C++ classes, you only need to prefix each class (not every single method)
I usually do it that way :
Note : The following also ensures portability...
Include File :
// my_macros.h
//
// Stuffs required under Windoz to export classes properly
// from the shared library...
// USAGE :
// - Add "-DBUILD_LIB" to the compiler options
//
#ifdef __WIN32__
#ifdef BUILD_LIB
#define LIB_CLASS __declspec(dllexport)
#else
#define LIB_CLASS __declspec(dllimport)
#endif
#else
#define LIB_CLASS // Linux & other Unices : leave it blank !
#endif
Usage :
#include "my_macros.h"
class LIB_CLASS MyClass {
}
Then, to build , simply :
-DBUILD_LIB
to the usual compiler command line -shared
to the usual linker command line 上一篇: 建立静态库的困难