c++ - 使用 g++ 创建共享库和静态库(在 Windows 下)

标签 c++ gcc dll shared-libraries static-libraries

如何使用 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/

相关文章:

java - Eclipse 未找到可执行 Jar 的库

c++ - 使用 OpenCV 改变图像的颜色

c - 为什么我无法通过整数加法获得最佳性能?

linux - 在 Kubuntu Linux 中更改 R 默认的 C/C++ 编译器

gcc - "Multiple include guards may be useful for"究竟是什么?

c# - 获取要传递给 System.IO.File 和默认流的 C 函数的 FILE* 句柄

c++ - 用于处理用户定义的类型和结构的模板

c++ - 为什么在 C++1y 的标准文件系统库扩展中没有获取用户/组信息的接口(interface)?

c++ - 异常方法签名中的 Throw 语句

c# - ILMerge 有点迷失