[英]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
额外细节:
.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.