如何使用 g++ 为 Windows 创建静态和动态库?
我找到了一些用于 Linux 的命令来创建 .so
文件,我尝试将它们应用到 Windows shell 上,但它们构建了 .dll
文件我的应用程序在运行时无法链接。
我只成功地使用 Visual C++ 构建了 .dll
文件,但我想在命令行上手动构建它们,最好使用 g++
。我还想知道如何为 Windows 构建静态库。
最佳答案
您需要在属性前加上前缀:
__declspec(dllexport)...
您要公开的所有功能。
参见 this .
C 函数示例:
__declspec(dllexport) int __cdecl Add(int a, int b)
{
return (a + b);
}
这可以使用 MACROS
进行简化:一切都在这个 helpful page 上进行了解释.
对于 C++ 类,您只需为每个类(而不是每个方法)添加前缀
我通常这样做:
Note : The following also ensures portability...
包含文件:
// 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
传递给常用的链接器命令行
关于c++ - 使用 g++ 创建共享库和静态库(在 Windows 下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17252946/