【问题标题】:Error LNK2028 when calling exported C function from C++ wrapper从 C++ 包装器调用导出的 C 函数时出现错误 LNK2028
【发布时间】:2013-12-22 18:14:33
【问题描述】:

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

Cproject 的最小示例如下所示:

测试.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++/CLIproject 调用此函数时

#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 文件

【问题讨论】:

  • 尝试在另一个源文件中声明f 的主体而不是标题。这能解决您的问题吗?
  • 从源文件中删除EXTERN_DLL_EXPORT。你只需要将它包含在头文件中。
  • @MaxTruxa 我没有将它包含在源文件中。在Test.h 我离开了EXTERN_DLL_EXPORT void f();。在Test.c 我写#include "Test.h"void f(){};它没有编译 (C2059)。
  • 你必须在你的 CLR 项目中 __declspec(dllimport) 你的函数。回家后我会为您制定解决方案。

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


【解决方案1】:

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 编译器将无法编译您的代码。

【讨论】:

  • 完美运行!我失去了最后 8 个小时试图完成这项工作。许多 tnx。
【解决方案2】:

我只花了 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2011-07-02
    相关资源
    最近更新 更多