关于 c :Cygwin GCC 与 Visual Studio 库的链接 | 珊瑚贝

Cygwin GCC linking with Visual Studio library


我使用 Visual Studio 2012 Express 创建了一个简单的库(静态 64 位 – .lib)。
这个库只有一个功能:

1
2
3
4
int get_number()
{
    return 67;
}

假设生成的库名为 NumTestLib64.lib.

我正在尝试使用 Cygwin64 编译一个简单的程序(我们称之为 test.cpp),它将链接 NumTestLib64.lib 并打印 get_number():

的结果

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>  

int get_number();

int main()
{
    printf(“get_number: %d\
, get_number());
    return 0;
}

很简单吧?显然不是。
使用 g++ -o test test.cpp -L. -lTestLibStatic64 编译返回:

1
2
3
/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 返回:

1
2
3
/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 或执行任何必要的更改,所有代码都是我的,无论是在这个简单的示例中还是在我正在开发的实际应用程序中。

请帮忙!

  • 您可以尝试在 get_number 之前使用 extern”C”
  • 我还认为您遇到的问题是,VS2012 和 GCC 使用不同的模型进行名称修改。恕我直言,解决此问题的唯一方法是将所有 API 方法定义为纯 c(使用 extern”C” 如上所述)。
  • 我试过了。在库代码的声明中添加了 extern “C”。甚至将整个项目更改为 C 项目(从 .cpp 更改为 .c)。还是不行。我得到一个”未定义的 get_num() 引用”错误。


找到答案了!关键是创建 *.dll 和 *.lib 文件。
*.lib 是在实际导出符号时创建的。
下面是创建的 DLL 的头文件(只有在 Visual Studio 中创建 DLL 时有效,创建静态库还不行):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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。


来源:https://www.codenong.com/24407762/

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?