我有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
其他详情:
.lib
文件答案 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