我有一个.c文件,我试图在VS2012中编译,但是我收到了这个错误:
error C2059: syntax error : '.' main.c
根据我所读到的,它是VS2012编译器的一个特定问题,我不会遇到其他编译器。无论这是否属实,我都希望有人能告诉我如何解决这个编译器错误。如何修改代码以便代码编译并且行为相同?
这就是我头文件中的内容:
struct mystruct
{
struct someOtherStruct obj2;
void* ptr1;
void* ptr2;
void* ptr3;
};
这就是我在main.c中所拥有的。
void* P1 = NULL;
void* P2 = NULL;
void* P3 = NULL;
/* VS2012 complains about this syntax */
static struct mystruct obj =
{
.ptr1 = P1,
.ptr2 = P2,
.ptr3 = P3,
};
void main(void)
{
/* Empty for now */
}
答案 0 :(得分:1)
Designated initializers是C99(或更新版本)功能,Visual Studio不支持C99(或更新版本)。等效的VS兼容初始化看起来像:
static struct mystruct obj =
{
{ 0 },
P1,
P2,
P3
};
如果您希望保留相同的代码,则Clang / LLVM和GCC都支持C11并可用于Windows。
答案 1 :(得分:1)
VS2013(最后)supports指定的初始值设定项,因此您必须升级编译器才能获得此功能。否则重写初始化程序,使其符合C89。
static struct mystruct obj =
{
{ /* initialize someOtherStruct members here */ },
P1, /* drop the member names */
P2,
P3,
};
如果您不想为编写someOtherStruct
的初始值设定项而烦恼,请重新排序mystruct
的成员,以便编译器自动将零初始化obj2
:
struct mystruct
{
void* ptr1;
void* ptr2;
void* ptr3;
struct someOtherStruct obj2;
};
static struct mystruct obj =
{
P1,
P2,
P3,
};