Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the warning in gcc 4.6: missing initializer [-Wmissing-field-initializers]?

The code

  GValue value = { 0 };

gives the following warning:

missing initializer [-Wmissing-field-initializers]

I know that's a GCC bug, but is there some trick to remove it? It is really not nice see such unreal warnings. But I don't want power off the warning because it will hide real warnings from me too. And sorry, but I can't update my GCC to 4.7 (where looks like it was fixed) version, yet.

like image 305
Jack Avatar asked Nov 14 '12 05:11

Jack


3 Answers

You could use:

-Wno-missing-field-initializers

to inhibit that warning specifically. Conversely, you could make it into an error with:

-Werror=missing-field-initializers

Both of these work with GCC 4.7.1; I believe they work with GCC 4.6.x too, but they don't work with all earlier versions of GCC (GCC 4.1.2 recognizes -Wno-missing-field-initializers but not -Werror=missing-field-intializers).

Obviously, the other way to suppress the warning is to initialize all fields explicitly. That can be painful, though.

like image 193
Jonathan Leffler Avatar answered Nov 09 '22 03:11

Jonathan Leffler


Use G_VALUE_INIT to initialize GValue-s. Their (private) structure is in /usr/include/glib-2.0/gobject/gvalue.h which #define G_VALUE_INIT appropriately.

I strongly disagree with your assessment that it is GCC's bug. You ask to be warned if a field is not explicitly initialized with -Wmissing-field-initializers and you get the warning you deserve.

Sadly G_VALUE_INIT is not documented, but it is here. Code with

GValue value = G_VALUE_INIT;

There is no universal solution to never get the warning about missing field initialization if -Wmissing-field-initializers is asked. When you ask for such a warning, you require the compiler to warn of every incomplete initializers. Indeed, the standard requires than all the non-explicitly initialized struct fields be zeroed, and gcc obeys the standard.

You could use diagnostic pragmas like

#pragma GCC diagnostic ignored "-Wmissing-field-initializers"

But my feeling is that you should code with care, and explicitly initialize all the fields. The warning you get is more a coding style warning (maybe you forgot a field!) than a bug warning.

I also believe that for your own (public) struct you should #define an initializing macro, if such struct are intended to be initialized.

like image 10
Basile Starynkevitch Avatar answered Nov 09 '22 03:11

Basile Starynkevitch


It also appears that using the .field-style of initialization, such as:

GValue value = { .somefield = 0 };

will cause the compiler to not issue the warning. Unfortunately if the struct is opaque, this is a non-starter.

like image 2
John Hascall Avatar answered Nov 09 '22 05:11

John Hascall