Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check in C++ that a struct is well aligned or contains gaps

Tags:

c++

c

I have a problem that a struct shall be checked - at compile time - if it is well aligned or if it contains gaps. The checking may be done in additional test code, but I don't want "packed" data in the real implementation code.

This is an example header file (MyData.h) with the typical include guards:

#ifndef MYDATA_H_
#define MYDATA_H_

struct uneven
{
  int bla_u32;
  short bla_u16;
  char bla_u8;
  /* <-- this gap will be filled in the unpacked version */
};

#endif // MYDATA_H

I found one possible solution - see below.

Questions:

  • Is there an elegant way to check if the struct uneven contains a different number of bytes compared to its unpacked counterpart at compile time?

  • Is there maybe even a solution that will work in C (without using a namespace)?

like image 986
michael_s Avatar asked Jul 27 '16 12:07

michael_s


1 Answers

You could use a function instead of a namespace (on ideone):

This solution also works in C

Header File:

typedef struct
{
  int bla_u32;
  short bla_u16;
  char bla_u8;

  /* <-- this gap will be filled in the unpacked version */
}  uneven;

Source File:

#include "MyData.h"

#define StaticAssert(cond, msg) switch(0){case 0:case cond:;}

void checkSizes()
{
  uneven unpacked_uneven;
#pragma pack(push, 1)
  #undef MYDATA_H_ // force re-including "MyData.h"
  #include "MyData.h"
#pragma pack(pop)
  uneven packed_uneven;
  StaticAssert(sizeof(unpacked_uneven) == sizeof(packed_uneven), "uneven contains gaps");
}

You can place your StaticAssert into the function for a compile time error.

like image 70
Dutow Avatar answered Oct 06 '22 00:10

Dutow