MSVC 中的链接错误 LNK2019,带有 __imp__ 前缀的未解析符号,但应该来自静态库

2023-12-23

我在 MSVC 中为我为 g++ 编写的项目遇到了链接问题。问题是这样的:

我将 libssh 构建为静态库,作为我的应用程序的一部分,并在 cmake 中添加目标

add_library(ssh_static STATIC $libssh_SRCS)

Libssh 是用 C 语言编写的,所以我用 'extern "C" {...}' 将包含内容包装在我的 C++ 源代码中。然后,我将 ssh_static 目标链接到我的可执行文件 sshconnectiontest,其中

target_link_libraries(sshconnectiontest ... ssh_static ...)

这一切在带有 gcc 的 linux 中工作得很好,但现在在 MSVC 中我得到了

error LNK2019: unresolved external symbol __imp__[function names here] referenced in [filename]

对于我使用的每个 libssh 函数。

知道出了什么问题吗?我在某处读到过imp前缀意味着链接器期望链接 .dll,但情况不应如此,因为 ssh_static 在 add_library 调用中被声明为静态库...


从我对 Windows 时代的记忆来看,在 MinGW 构建的 DLL 中,__imp__符号前缀用于调用 DLL 的 Trampoline 函数。然后,这个符号由一个小型静态库提供,扩展名为.dll.a.

当您包含 libssh 标头时,您需要设置#define表明您希望静态链接。如果不这样做,标头中的 libssh 函数将被声明__declspec(dllimport)所以__imp__符号将在链接时出现。

我查看了 libssh 源代码并在顶部找到了它libssh.h:

#ifdef LIBSSH_STATIC
  #define LIBSSH_API
#else
  #if defined _WIN32 || defined __CYGWIN__
    #ifdef LIBSSH_EXPORTS
      #ifdef __GNUC__
        #define LIBSSH_API __attribute__((dllexport))
      #else
        #define LIBSSH_API __declspec(dllexport)
      #endif
    #else
      #ifdef __GNUC__
        #define LIBSSH_API __attribute__((dllimport))
      #else
        #define LIBSSH_API __declspec(dllimport)
      #endif
    #endif
  #else
    #if __GNUC__ >= 4
      #define LIBSSH_API __attribute__((visibility("default")))
    #else
      #define LIBSSH_API
    #endif
  #endif
#endif

你需要定义LIBSSH_STATIC,或者通过#define之前#include <libssh.h>线,或作为/D选项。由于您使用的是 CMake,因此您可能会通过以下方式执行此操作add_definitions in CMakeLists.txt.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MSVC 中的链接错误 LNK2019,带有 __imp__ 前缀的未解析符号,但应该来自静态库 的相关文章

随机推荐