[英]Cygwin GCC linking with Visual Studio library
我使用Visual Studio 2012 Express創建了一個簡單的庫(靜態64位 - .lib)。 所有這個庫都有一個功能:
int get_number()
{
return 67;
}
假設生成的lib名為NumTestLib64.lib
。
我正在嘗試使用Cygwin64編譯一個簡單的程序(讓我們稱之為test.cpp
),它將鏈接NumTestLib64.lib
並將打印get_number()
的結果:
#include <stdio.h>
int get_number();
int main()
{
printf("get_number: %d\n", get_number());
return 0;
}
很簡單吧? 顯然不是。
使用g++ -o test test.cpp -L. -lTestLibStatic64
編譯g++ -o test test.cpp -L. -lTestLibStatic64
g++ -o test test.cpp -L. -lTestLibStatic64
返回:
/tmp/ccT57qc6.o:test.cpp:(.text+0xe): undefined reference to `get_number()'
/tmp/ccT57qc6.o:test.cpp:(.text+0xe): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `get_number()'
collect2: error: ld returned 1 exit status
並且, g++ -o test test.cpp TestLibStatic64.lib
返回:
/tmp/ccMY8yNi.o:test.cpp:(.text+0xe): undefined reference to `get_number()'
/tmp/ccMY8yNi.o:test.cpp:(.text+0xe): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `get_number()'
collect2: error: ld returned 1 exit status
我正在尋找能夠在Visual Studio方面和Cygwin命令行方面提供指令的勇敢者,以了解如何完成這項工作。
我已經嘗試了所有可能的網頁,所以可能鏈接無濟於事,只是確切的說明。 我不介意將庫更改為DLL或執行任何必要的更改,所有代碼都是我的,在這個簡單的示例和我正在開發的實際應用程序中。
請幫忙!
找到答案了! 關鍵是創建* .dll和* .lib文件。 實際導出符號時會創建* .lib。 下面是創建的DLL的頭文件(在Visual Studio中創建DLL時,onlty工作,創建靜態庫不起作用):
#ifdef TESTLIB_EXPORTS
#define TESTLIB_API __declspec(dllexport)
#else
#define TESTLIB_API __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
TESTLIB_API int get_num();
#ifdef __cplusplus
}
#endif
當然, TESTLIB_EXPORTS
僅在DLL項目中定義。 由於__declspec(dllimport)
部分,鏈接到此DLL的main將使用此標頭非常重要。 此外,正如評論員所建議的那樣, extern "C"
是必須的,以避免損壞。 此外,我已成功連接Cygwin32和MinGW32,而不是Cygwin64。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.