c++ - 在 Visual Studio 中的同一解决方案中构建 C 项目以调用 C++ 库中的函数

标签 c++ c visual-studio

在 Visual Studio 中,是否可以在同一解决方案中使用一个包含 C++ 库的项目和另一个使用 C 编写的项目,并使用 C 调用该库中的函数?

我在库标题中有什么:

#ifdef __cplusplus
  #define EXTERN extern "C"
#else
  #define EXTERN
#endif

#ifndef LIB_API
  #ifndef LIB_STATIC
    #ifdef LIB_EXPORT
      #define LIB_API EXTERN __declspec(dllexport)
    #else
      #define LIB_API EXTERN __declspec(dllimport)
    #endif
  #else
    #define LIB_API
  #endif
#endif

LIB_API uint32_t Func(int8_t *arg);

我想从我的 C 项目静态链接到此库,因此我从库项目中选择依赖项,在预处理器定义中定义宏 LIB_STATIC,选择“编译为 C 代码 (/TC)”选项并调用此函数。我得到的是链接器错误

error LNK2019: unresolved external symbol _Func referenced in function _main

当我查看 lib 文件时,我可以找到类似 Func 的内容,而不是 _Func。我做错了什么?

(忘记添加,库的.cpp模块中有适当的函数实现)

Angew 和 AnatolyS 的回答

我们需要在静态库情况下将 LIB_API 定义为 EXTERN,因此正确的预处理器 block 将是:

#ifndef LIB_API
  #ifndef LIB_STATIC
    #ifdef LIB_EXPORT
      #define LIB_API EXTERN __declspec(dllexport)
    #else
      #define LIB_API EXTERN __declspec(dllimport)
    #endif
  #else
    #define LIB_API EXTERN
  #endif
#endif

最佳答案

要从 C 代码中使用 C++ 函数,您必须将此类函数导出为 C,因此请更改 LIB_API 的定义以进行静态链接:

#else
 #define LIB_API EXTERN
#endif

关于c++ - 在 Visual Studio 中的同一解决方案中构建 C 项目以调用 C++ 库中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15221876/

相关文章:

c - 将 uint8_t 中的位地址作为结构体的成员

php - 将具有 NULL 字符的内存块从 C 传输到 PHP 程序

php - 使用 HIPHOP 编译 PHP

c++ - 无法使用 g++ 导入共享库

c++ - O(n) 算法找出出现超过 n/2 次的元素

c - 初始化结构的矩阵(双指针)成员

c++ - 使用 Qt 程序构建 crypto++ 时出现链接器错误

visual-studio - 从 Azure DevOps 克隆时如何选择首选的 Visual Studio 版本

c# - 符号已创建,但调试永远不会在断点处停止

c++ - Qt编译错误: 'emit' was not declared in this scope