我正在通过gnome gtk +网站查看tutorial,我是gtk +的新手,而不是c中的高级版。我在使用这段代码时遇到了一些问题:
static GActionEntry app_entries[] = {
{"preferences", preferences_activated, NULL, NULL, NULL},
{"quit", quit_activated, NULL, NULL, NULL}
};
当我用-Wextra -Wall -g -O2 -pedantic-errors
编译它时,它会抛出缺少的初始化器警告:
gcc -c -o app.o -Wextra -Wall -O2 -pedantic-errors -g `pkg-config --cflags gtk+-3.0` app.c
app.c:38:2: warning: missing initializer for field ‘padding’ of ‘GActionEntry’ [-Wmissing-field-initializers]
{ "preferences", preferences_activated, NULL, NULL, NULL },
^
In file included from /usr/include/glib-2.0/gio/gio.h:31:0,
from /usr/include/gtk-3.0/gdk/gdkapplaunchcontext.h:28,
from /usr/include/gtk-3.0/gdk/gdk.h:32,
from /usr/include/gtk-3.0/gtk/gtk.h:30,
from app.c:1:
/usr/include/glib-2.0/gio/gactionmap.h:72:9: note: ‘padding’ declared here
gsize padding[3];
^
app.c:39:2: warning: missing initializer for field ‘padding’ of ‘GActionEntry’ [-Wmissing-field-initializers]
{ "quit", quit_activated, NULL, NULL, NULL }
^
In file included from /usr/include/glib-2.0/gio/gio.h:31:0,
from /usr/include/gtk-3.0/gdk/gdkapplaunchcontext.h:28,
from /usr/include/gtk-3.0/gdk/gdk.h:32,
from /usr/include/gtk-3.0/gtk/gtk.h:30,
from app.c:1:
/usr/include/glib-2.0/gio/gactionmap.h:72:9: note: ‘padding’ declared here
gsize padding[3];
^
为什么我收到这个警告?我该如何解决?
提前致谢
答案 0 :(得分:1)
查看头文件/usr/include/glib-2.0/gio/gactionmap.h,我们发现GActionEntry
的定义如下:
struct _GActionEntry
{
const gchar *name;
void (*activate) (GSimpleAction *action, GVariant *parameter, gpointer user_data);
const gchar *parameter_type;
const gchar *state;
void (* change_state) (GSimpleAction *action, GVariant *value, gpointer user_data);
/*< private >*/
gsize padding[3];
};
typedef struct _GActionEntry GActionEntry;
查看结构的最后一个成员?如果您要为“缺少初始化程序”启用警告,则需要为其提供初始化程序。
尝试这样的事情:
static GActionEntry app_entries[] = {
{"preferences", preferences_activated, NULL, NULL, NULL, {0,0,0}},
{"quit", quit_activated, NULL, NULL, NULL, {0,0,0}}
};
答案 1 :(得分:0)
在Brad. S中注明reply,这是因为GActionEntry有一个私有&#34;填充&#34;字段,在您的代码中未初始化。 GCC警告你。
但是,您可以使用指定的初始化程序来欺骗GCC。看看GCC Warning Options。
-Wmissing场-初始化
此选项不会警告指定的初始值设定项,因此以下修改不会触发警告:
struct s { int f, g, h; }; struct s x = { .f = 3, .g = 4 };
如果要仅初始化结构的几个字段,则指定的初始值设定项非常有用。根据C99标准,未初始化的字段将设置为零。
(C99第6.7.8.19节)&#34;如果括号括起的列表中的初始值设定项少于聚合的元素或成员,或者用于初始化已知大小的数组的字符串文字中的字符数较少与数组中的元素相比,聚合的其余部分应与具有静态存储持续时间的对象隐式初始化。&#34;
通过使用指定的初始值设定项,您的代码可能如下所示:
static GActionEntry app_entries[] = {
{ .name = "preferences", .activate = preferences_activated },
{ .name = "quit", .activate = quit_activated }
};
这些代码不会引起海湾合作委员会的警告。
当然,GCC无法区分您故意省略的字段以及您真正忘记初始化的字段。通过使用此语法,您将不再获得警告,而是您自己。
另请注意,指定的初始化程序在C99之前不存在于C中。