如何使用g ++为Windows创建静态和动态库?
我发现了一些Linux用于创建.so
文件的命令,我尝试在Windows shell上应用它们,但是它们构建了我的应用程序无法链接的.dll
文件运行。
我只是设法使用Visual C ++构建.dll
文件,但我想在命令行上手动构建它们,最好使用g++
。我也想知道如何为Windows构建静态库。
答案 0 :(得分:1)
您需要使用属性前缀:
__declspec(dllexport)...
您要公开的所有功能。
请参阅this。
C函数示例:
__declspec(dllexport) int __cdecl Add(int a, int b)
{
return (a + b);
}
可以使用MACROS
简化此操作:所有问题都在此helpful page上解释。
对于C ++类,您只需要为每个类添加前缀(而不是每个方法)
我通常这样做:
注意:以下内容还可确保可移植性......
包含文件:
// 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
用法:
#include "my_macros.h"
class LIB_CLASS MyClass {
}
然后,构建,只需:
-DBUILD_LIB
传递给通常的编译器命令行-shared
传递给通常的链接器命令行