mercredi 6 septembre 2017

Filling in padding bytes of a C struct in C++? (NOT concerning struct packing!)

I am using a library with a struct that has 3 officially documented members, but its implemented actually contains 4. The last one is a byte array that is used for padding. This is a common technique in C to stay ABI compatible: add a bunch of bytes at the end, and if later versions add members to the struct, this padding area is shrunk accordingly. In total, the size of the struct stays the same.

But now I have to use this struct in C++, and I am using it for a static const value, so I need to initialize it using an initializer list. So, like this:

static const foo_struct foo = { 1, 2, 3 };

Since this does not initialize the fourth value, GCC prints out:

warning: missing initializer for member ‘foo_struct::padding’ [-Wmissing-field-initializers]

A constructor syntax like foo(1,2,3) would not work, since this is a C struct. And setting it to {0} is no option either, since I must initialize the first three members.

Is there a C++11/C++14 conform way of dealing with this warning?

EDIT: Simply using { 1, 2, 3, 0 } might work, but is unstable, since the padding area is undocumented. Also, if future versions add a member, then it would sum up to 5 members, and the warning would return.

Aucun commentaire:

Enregistrer un commentaire