The Linux Page

How do you force the size of a C/C++ struct to a given size?

Once in a while, I want to create a struct which has a specific size because it has to match a file one to one.

To do that, you can use a simple trick which is to use a union instead of a struct.

union header_t
    char unused[total_size];
        int field1;
        int field2;
        int field3;

Note that the total size of the union may end up being more than total_size. It's up to you to assert that the size does not go over. However, this is an easy way to create a struct which has a hard coded size. However, it will not be properly cleared in C++11 (in case you set field1, field2, ... the end of the struct will not be zeroes). In my case it's not so bad because I want to mmap() that structure to my file and the file will be all zeroes anyway.

In C++11 or better, you have a static_assert() you can use to verify that the size is correct:

static_assert(sizeof(header_t) == total_size,
                   "invalid header_t struct size");

This is important if you expect to grow your struct over time and want to make sure it doesn't go out of control.