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

时间:2013-12-22 18:14:34

标签: c++ visual-studio linker-errors dllexport

我有C项目,我从中导出函数f()并从其他C ++项目调用它,它工作正常。但是,当我在g()内调用其他函数f时,我收到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文件

2 个答案:

答案 0 :(得分:2)

<强> 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)导入的功能已无法定义。

其他变化:

  • 永远不要在没有extern "C"后卫的情况下编写#ifdef __cplusplus,否则许多C编译器都无法编译您的代码。

答案 1 :(得分:0)

我花了两天时间来解决这个完全相同的问题。谢谢你的解决方案。我想延长它。

在我的情况下,我从导出的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