从包装器调用导出C++ C 函数时LNK2028错误

Error LNK2028 when calling exported C function from C++ wrapper

本文关键字:函数 LNK2028 错误 C++ 包装 调用      更新时间:2023-10-16

我有 C 项目,我从中导出函数f()并从其他C++项目中调用它,它工作正常。但是,当我调用f内部的其他函数g()时LNK2028出现错误。

C项目的最小示例如下所示:

测试.h

#ifndef TEST_H
#define TEST_H
#include "myfunc.h"
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT void f()
{
    g();    // this will provide LNK2028 if f() is called from other project
}
#endif

myfunc.h

void g();

myfunc.c

#include "myfunc.h"
void g(){}

项目本身正在建设中。但是,当我从其他C++/CLI项目中调用此函数时

#include "Test.h"
public ref class CppWrapper
{
 public:
    CppWrapper(){ f(); }   // call external function        
};

我收到错误:

error LNK2028: unresolved token (0A00007C) "void __cdecl g(void)" (?g@@$$FYAXXZ) referenced in function "extern "C" void __cdecl f(void)" (?f@@$$J0YAXXZ)   main.obj    CppWrapper
error LNK2019: unresolved external symbol "void __cdecl g(void)" (?g@@$$FYAXXZ) referenced in function "extern "C" void __cdecl f(void)" (?f@@$$J0YAXXZ)    main.obj    CppWrapper

其他详细信息:

  1. 我为整个解决方案设置了x64平台
  2. 在CppWrapper中,我包含来自C项目的.lib文件

Test.h

#ifndef TEST_H
#define TEST_H
#ifdef BUILDING_MY_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
DLL_EXPORT void f();
#ifdef __cplusplus
}
#endif
#endif

测试.c

#include "Test.h"
#include "myfunc.h"
void f()
{
    g();
}

在 C 项目中,您必须将BUILDING_MY_DLL添加到

Configuration Properties > C/C++ > Preprocessor > Preprocessor Definitions

唯一真正的变化是我在__declspec(dllexport)__declspec(dllimport)之间添加了切换。所需更改:

  • 已将f 的主体移至Test.c,因为使用 __declspec(dllimport) 导入的函数尚未具有定义。

其他更改:

  • 切勿在没有#ifdef __cplusplus防护的情况下编写extern "C",否则许多 C 编译器将无法编译您的代码。

我只花了 2 天时间与这个完全相同的问题作斗争。 感谢您的解决方案。 我想扩展它。

就我而言,我正在从导出的c ++ dll函数调用c函数,并且遇到了相同的错误。 我能够修复它(使用您的示例)

#ifndef TEST_H
#define TEST_H
#ifdef BUILDING_MY_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
#include "myfunc.h"
#ifdef __cplusplus
}
#endif
#endif