2013-06-22 67 views
2

如何使用g ++爲Windows創建靜態和動態庫?使用g ++創建共享和靜態庫(在Windows下)

我發現了一些用於創建.so文件的Linux命令,我試圖將它們應用於Windows shell,但是它們生成.dll文件,我的應用程序在運行時無法鏈接。

我只設法使用Visual C++構建.dll文件,但我想在命令行上手動構建它們,最好使用g++。我也想知道如何爲Windows構建靜態庫。

+0

這不是那麼微不足道,當你在Linux下使用'-shared做的-fPIC'方式。 –

回答

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平時的鏈接器命令行
+0

對於靜態庫,只需將'-static'而不是'-shared'傳遞給鏈接器。 (例如'gcc -o mylib.lib -static * .o -Wl, - subsystem,windows')。 –

+0

非常感謝你!我會試試這個。再次感謝 –

+0

很高興提供幫助。乾杯! –