如何将C-struct指定的初始化程序重写为C89(resp MSVC C编译器)

伙计们,我有这个问题:

通常在C99 GCC(cygwin / MinGW / linux)中,C struct中的初始化器有点符号语法。
像这样:

//HELP ME HOW TO REWRITE THIS (in most compact way) to MSVC static struct my_member_t my_global_three[] = { {.type = NULL, .name = "one"}, {.type = NULL, .name = "two"}, {.type = NULL, .name = "three"}, }; 

my_memeber_t定义在头文件中:

 struct my_member_t { struct complex_type * type; char * name; int default_number; void * opaque; }; 

我在MSVC 9.0 (Visual Studio 2008)中编译linux代码,在cygwin / MinGW上这可以正常工作。
但是cl无法编译这个(因为C99实现很糟糕): error C2059: syntax error : '.'

PROBLEM:
How to rewrite (many) global structs in a way that MSVC
PROBLEM:
How to rewrite (many) global structs in a way that MSVC
(resp C89) can compile it? PROBLEM:
How to rewrite (many) global structs in a way that MSVC
can compile it?


致以最诚挚的问候和感谢…

悲惨的C99实施? 我不认为VC2008中的C编译器甚至试图实现C99。 它可能会借用一些function,但它实际上是一个C89 / 90编译器。

只需删除字段名称标签即可

 static struct my_member_t my_global_three[] = { { NULL, "one"}, { NULL, "two"}, { NULL, "three"}, }; 

在这种情况下,它很容易,因为原始代码中的初始值设定项的顺序与结构中字段的顺序相同。 如果订单不同,您必须在无标签C89 / 90版本中重新排列它们。

如果它确实是你的 my_member_t ,那么你应该将字符串指针声明为const char *或停止使用字符串文字初始化这些成员。

感谢您的信息,Nico。

但是,我发现内部数组的结构不起作用。 我建议这个修改适用于C99和MSVC(在MSVC ++ 2010 Express中validation):

 #ifdef HAVE_DESIGNATED_INITIALIZERS #define SFINIT(f, ...) f = __VA_ARGS__ #else #define SFINIT(f, ...) __VA_ARGS__ #endif typedef struct { int val; int vecB[4]; int vecA[4]; } MyStruct_ts; static const MyStruct_ts SampleStruct = { SFINIT(.val , 8), SFINIT(.vecB , { 1, -2, 4, -2}), SFINIT(.vecA , { 1, -3, 5, -3}), }; 

这样,您可以将一个文件用于MSVC和其他编译器。

 /* * Macro for C99 designated initializer -> C89/90 non-designated initializer * * Tested. Works with MSVC if you undefine HAVE_DESIGNATED_INITIALIZERS. Cscope also * groks this. * * ("SFINIT" == struct field init, but really, it can be used for array initializers too.) */ #ifdef HAVE_DESIGNATED_INITIALIZERS #define SFINIT(f, v) f = v #else #define SFINIT(f, v) v #endif struct t { char f1; int f2; double f3; }; struct tt = { SFINIT(.f1, 'a'), SFINIT(.f2, 42), SFINIT(.f3, 8.13) };