2013-12-22 15 views
1

我有從中導出函數f()並從其他C++項目中調用它的C項目,它工作正常。但是,當我呼叫內部的其他功能g()時,我得到LNK2028錯誤。從C++包裝器調用導出的C函數時出錯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(){} 

的幻燈ct本身正在建造中。然而,當我打電話從其他C++/CLI項目這個功能

#include "Test.h" 
public ref class CppWrapper 
{ 
public: 
    CppWrapper(){ f(); } // call external function   
}; 

我得到錯誤:

error LNK2028: unresolved token (0A00007C) "void __cdecl g(void)" ([email protected]@$$FYAXXZ) referenced in function "extern "C" void __cdecl f(void)" ([email protected]@$$J0YAXXZ) main.obj CppWrapper 
error LNK2019: unresolved external symbol "void __cdecl g(void)" ([email protected]@$$FYAXXZ) referenced in function "extern "C" void __cdecl f(void)" ([email protected]@$$J0YAXXZ) main.obj CppWrapper 

其他細節:

  1. 我設置的x64平臺整體解決方案
  2. 在CppWrapper我包括來自C項目的.lib文件
+0

嘗試在另一個源文件而不是頭中聲明'f'的主體。這是否解決了您的問題? –

+0

@MaxTruxa不,在'Test.c'中包含'Test.h'時,我在'void f()'之前爲'EXTERN_DLL_EXPORT'的C2059編譯錯誤。 – Dejan

+0

從源文件中刪除'EXTERN_DLL_EXPORT'。您只需將其包含在頭文件中。 –

回答

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 

唯一真正的變化是我添加了0123之間的切換和__declspec(dllimport)。需要進行更改:

  • 感動f的身體Test.c因爲__declspec(dllimport)導入函數不能有一個定義了。

其他變化:

  • 難道從來不寫extern "C"沒有#ifdef __cplusplus後衛,或許多C編譯器不會編譯代碼。
+0

它工作完美!我最後8個小時試圖完成這項工作。許多tnx。 – Dejan

0

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