Struct padding in C++

No. That is not possible. It’s because of lack of standardization of C++ at the binary level.

Don Box writes (quoting from his book Essential COM, chapter COM As A Better C++)

C++ and Portability

Once the decision is made to
distribute a C++ class as a DLL, one
is faced with one of the fundamental
weaknesses of C++
, that is, lack of
standardization at the binary level
.
Although the ISO/ANSI C++ Draft
Working Paper attempts to codify which
programs will compile and what the
semantic effects of running them will
be, it makes no attempt to standardize
the binary runtime model of C++
. The
first time this problem will become
evident is when a client tries to link
against the FastString DLL’s import library from
a C++ developement environment other
than
the one used to build the
FastString DLL.

Struct padding is done differently by different compilers. Even if you use the same compiler, the packing alignment for structs can be different based on what pragma pack you’re using.

Not only that if you write two structs whose members are exactly same, the only difference is that the order in which they’re declared is different, then the size of each struct can be (and often is) different.

For example, see this,

struct A
{
   char c;
   char d;
   int i;
};

struct B
{
   char c;
   int i;
   char d;
};

int main() {
        cout << sizeof(A) << endl;
        cout << sizeof(B) << endl;
}

Compile it with gcc-4.3.4, and you get this output:

8
12

That is, sizes are different even though both structs have the same members!

The bottom line is that the standard doesn’t talk about how padding should be done, and so the compilers are free to make any decision and you cannot assume all compilers make the same decision.

Leave a Comment