繁体   English   中英

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

[英]Error LNK2028 when calling exported C function from C++ wrapper

我有一个C项目,可以从中导出函数f()并从其他C ++项目中调用它,并且工作正常。 但是,当我在f内调用其他函数g() LNK2028错误。

C项目的最小示例如下:

Test.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

TEST.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函数调用ac函数,但遇到了相同的错误。 我能够修复它(使用您的示例)

#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM