0

我有类型:

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))
4

2 回答 2

2

我做了一个简单的程序:

#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;
}

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

于 2015-08-05T20:58:11.540 回答
0

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

#include <stddef.h>

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

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

于 2015-08-05T21:00:37.167 回答