gpt4 book ai didi

c++ - Cygwin GCC 与 Visual Studio 库链接

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:10:04 25 4
gpt4 key购买 nike

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

int get_number()
{
return 67;
}

假设生成的库名为 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 返回:

/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 时有效,创建静态库还不行):

#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 的主体将使用此 header 很重要。此外,正如评论员所建议的那样,extern "C" 是必须的,以避免混淆。此外,我已经成功地在 Cygwin32 和 MinGW32 上进行了链接,而不是在 Cygwin64 上。

关于c++ - Cygwin GCC 与 Visual Studio 库链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24407762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com