【问题标题】:Creating shared and static libraries using g++ (under Windows)使用 g++ 创建共享库和静态库(在 Windows 下)
【发布时间】:2013-06-22 16:38:17
【问题描述】:

如何使用 g++ 为 Windows 创建静态和动态库?

我找到了一些用于 Linux 的命令来创建 .so 文件,并且我尝试将它们应用到 Windows shell 上,但是它们构建了 .dll 文件,而我的应用程序在运行时无法链接到这些文件。

我只设法使用 Visual C++ 构建 .dll 文件,但我想在命令行上手动构建它们,最好使用 g++。我也想知道如何为 Windows 构建静态库。

【问题讨论】:

  • 这在你使用 linux -shared -fPIC 的方式时并不是那么简单。

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


【解决方案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 传递给常用的链接器命令行

【讨论】:

  • 对于静态库,只需将 -static 而不是 -shared 传递给链接器。 (例如gcc -o mylib.lib -static *.o -Wl,--subsystem,windows)。
猜你喜欢
  • 2015-10-11
  • 2011-05-17
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多