【问题标题】:Visual Studio Syntax Error on offsetof()offsetof() 上的 Visual Studio 语法错误
【发布时间】:2015-10-28 19:20:10
【问题描述】:

我有类型:

typedef struct 
{
   int x;
   int y;
   int z; 
} sdf_test_t;

但是当我尝试编译以下内容时:

offset = offsetof(sdf_test_t, z);

Visual Studio 响应:

c:\dataflash.c(542) : error C2143: syntax error : missing ')' before 'type'
c:\dataflash.c(542) : error C2059: syntax error : ')'

这里有什么问题?

我正在使用:

Microsoft Visual Studio 2008 x86 
Microsoft (R) Visual Studio Version 9.0.21022.8.

offsetof 宏在<stddef.h> 中定义如下:

/* Define offsetof macro */
#ifdef __cplusplus

#ifdef  _WIN64
#define offsetof(s,m)   (size_t)( (ptrdiff_t)&reinterpret_cast<const volatile char&>((((s *)0)->m)) )
#else
#define offsetof(s,m)   (size_t)&reinterpret_cast<const volatile char&>((((s *)0)->m))
#endif

#else

#ifdef  _WIN64
#define offsetof(s,m)   (size_t)( (ptrdiff_t)&(((s *)0)->m) )
#else
#define offsetof(s,m)   (size_t)&(((s *)0)->m)
#endif

#endif  /* __cplusplus */

通过消除。我已经确定编译器使用:

#define offsetof(s,m)   (size_t)&reinterpret_cast<const volatile char&>((((s *)0)->m))

【问题讨论】:

    标签: visual-studio visual-c++ visual-studio-2008 offsetof


    【解决方案1】:

    我已经做了一个简单的程序:

    #include <stddef.h>
    
    typedef struct 
    {
      int x;
      int y;
      int z; 
    } sdf_test_t;
    
    int main() {
      size_t offset = offsetof(sdf_test_t, z);
      return 0;
    }
    

    我没有任何问题,我认为你可以尝试将代码隔离在另一个项目中并再次测试。

    【讨论】:

    • 谢谢。我发现关键是我必须包含&lt;stddef.h&gt;,因此它将使用宏的C 变体,而不是默认的C++ 变体。
    【解决方案2】:

    我设法通过在我的源文件中添加以下行来修复它:

    #include <stddef.h>
    

    由此看来,如果您没有明确包含头文件,Visual Studio 似乎会默默地包含头文件。更糟糕的是,它默认源文件是C++

    如果我不包含带有我使用的符号的头文件,我希望编译器会尖叫并报告错误,而不仅仅是编造一些东西......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 2016-03-08
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      相关资源
      最近更新 更多