【问题标题】:Syntax error C2059 when building building C application using C/C++ DLL header使用 C/C++ DLL 标头构建构建 C 应用程序时出现语法错误 C2059
【发布时间】:2015-03-05 20:41:10
【问题描述】:

我正在尝试将 C++ DLL 头文件转换为与 C/C++ 兼容的头文件。虽然我已经掌握了大部分主要结构,但我遇到了最后一个我似乎无法解释的编译器问题。以下代码在 C++ 中运行良好,但是当我尝试编译仅包含此文件的 C 应用程序时,我的头文件中的函数定义出现错误。

代码.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'

Google 搜索未生成任何相关结果。以下线程很接近,但不能完全回答我的问题:

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

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

为什么会出现这种语法错误?

【问题讨论】:

  • 删除(LIB_API)周围的(),然后重试。
  • 这会导致更多错误:错误 C2143:语法错误:在 '' 之前缺少 ')' 错误 C2143:语法错误:在 '' 之前缺少 '{' 错误 C2059:语法错误:')'
  • 对不起,我对你开枪了。你说的对。一旦我实现了下面的答案,我遇到了另一个通过删除括号来解决的问题。谢谢!

标签: c++ c visual-studio dll


【解决方案1】:

在 C 中,结构不是类型,因此您必须使用 struct Fooenum Bar,而在 C++ 中您可以使用 FooBar

注意事项:

  • 在 C++ 中,即使类型是类,您仍然可以使用旧语法。
  • 在 C 中,人们经常使用 typedef struct Foo Foo,它允许使用与当时 C++ 中相同的语法。

【讨论】:

  • 上当了,马特,你可能会受到这里提到的后一种方法的最小影响,typedef struct ToolState {....} ToolState; 如果你使用相同的 MS 工具链,其余代码应该不需要任何更改C 和 C++ 编译。
  • 谢谢你们俩。我感谢额外的注释和建议。他们非常有帮助。现在一切正常。 :)
猜你喜欢
  • 2018-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 2017-08-05
  • 2022-07-04
相关资源
最近更新 更多