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

时间:2013-06-22 16:38:17

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

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

我发现了一些Linux用于创建.so文件的命令,我尝试在Windows shell上应用它们,但是它们构建了我的应用程序无法链接的.dll文件运行。

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

1 个答案:

答案 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传递给通常的链接器命令行