从包装器调用导出C++ C 函数时LNK2028错误
Error LNK2028 when calling exported C function from C++ wrapper
我有 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
其他详细信息:
- 我为整个解决方案设置了x64平台
- 在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
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 从包装器调用导出C++ C 函数时LNK2028错误
- 调用WinSnmp函数SnmpStartup时出现错误LNK2028