2015-01-07 43 views
1

我試圖將C++ DLL頭文件翻譯成C/C++兼容頭文件。雖然我已經掌握了大部分主要的構造,但我遇到了最後一個編譯器問題,我似乎無法解釋。下面的代碼在C++中工作正常,但是當我試圖編譯一個只包含這個文件的C應用程序時,我在我的頭文件中得到了函數定義的錯誤。當使用C/C++ DLL頭構建C應用程序時,語法錯誤C2059

Code.h:

typedef void *PVOID; 
typedef PVOID HANDLE; 
#define WINAPI __stdcall 

#ifdef LIB_EXPORTS 
    #define LIB_API __declspec(dllexport) 
#else 
    #define LIB_API __declspec(dllimport) 
#endif 

struct ToolState 
{ 
    HANDLE DriverHandle; 
    HANDLE Mutex; 
    int LockEnabled; 
    int Type; 
}; 

#ifdef __cplusplus 
extern "C" { 
#endif 

(LIB_API) int SetRate(ToolState *Driver, int rate); 

(LIB_API) void EnableLock(ToolState *Driver) ; 

(LIB_API) int SendPacket(ToolState *Driver, unsigned char *OutBuffer, int frameSize); 

//These also give me the same error: 
//LIB_API WINAPI int SendPacket(ToolState *Driver, unsigned char *OutBuffer, int frameSize); 
//__declspec(dllimport) WINAPI int SendPacket(ToolState *Driver, unsigned char *OutBuffer, int frameSize); 

//Original C++ call that works fine with C++ but has multiple issues in C 
//LIB_API int SetRate(ToolState *Driver, int rate); 

#ifdef __cplusplus 
} 
#endif 

錯誤:

error C2059: syntax error : 'type' 
error C2059: syntax error : 'type' 
error C2059: syntax error : 'type' 

谷歌搜索還沒有產生任何相關的結果。以下主題是接近,但不完全回答我的問題:

C2059 syntax error using declspec macro for one function; compiles fine without it

http://support.microsoft.com/kb/117687/en-us

這是爲什麼語法錯誤出現?

+1

刪除'()'周圍的'(LIB_API)'並重試。 – wilx

+0

這會導致更多的錯誤: 錯誤C2143:語法錯誤:缺少')'之前'*' 錯誤C2143:語法錯誤:缺少'{'之前'*' 錯誤C2059:語法錯誤:')' – Matt

+0

對不起,我跳了槍在你身上。你是對的。一旦我實現了下面的答案,我遇到了另一個通過刪除括號修復的問題。謝謝! – Matt

回答

3

在C中,結構體不是類型,所以您必須使用struct Fooenum Bar,在C++中您可以使用FooBar

注:

  • 在C++中,你仍然可以使用舊的語法,即使類型爲一類。
  • 在C中,人們經常使用​​,它允許使用與C++相同的語法。
+1

不要緊,Matt,你可能會受到後面提到的方法的最小打擊,'typedef struct ToolState {....} ToolState;'如果你使用相同的代碼,其餘代碼不需要改變用於C和C++編譯的MS工具鏈。 – WhozCraig

+0

謝謝你們兩位。我欣賞額外的筆記和建議。他們非常有幫助。現在一切正常。 :) – Matt

相關問題