I want to add code that during compilation checks the size of a structure to make sure that it is a predefined size. For example I want to make sure that the size of this structure is 1024 byte when I am porting this code or when I am adding/removing items from structure during compile time:
#pack(1) struct mystruct { int item1; int item2[100]; char item3[4]; char item5; char padding[615]; }
I know how to do this during run time by using a code such as this:
if(sizeof(mystruct) != 1024) { throw exception("Size is not correct"); }
But it is a waste of processing if I do this during run time. I need to do this during compile time.
How can I do this during compilation?
sizeof is evaluated at compile time, but if the executable is moved to a machine where the compile time and runtime values would be different, the executable will not be valid.
It is not possible because some inputs are not known until runtime.
If you want to manually count it, the size of a struct is just the size of each of its data members after accounting for alignment. There's no magic overhead bytes for a struct.
In 32 bit processor, it can access 4 bytes at a time which means word size is 4 bytes. Similarly in a 64 bit processor, it can access 8 bytes at a time which means word size is 8 bytes. Structure padding is used to save number of CPU cycles.
You can check the size during compilation:
static_assert (sizeof(mystruct) == 1024, "Size is not correct");
You need C++11 for that. Boost has a workaround for pre-c++11 compilers:
BOOST_STATIC_ASSERT_MSG(sizeof(mystruct) == 1024, "Size is not correct");
See the documentation.
If you don't have C++11 or Boost, you could try this:
typedef char assertion_on_mystruct[( sizeof(mystruct)==1024 )*2-1 ];
If the statement is false, then this typedefs an array type with negative size, and your compiler should give an error message. If true, then the size will be one, a valid size. For example, g++ gives:
template.cpp:10:70: error: size of array ‘assertion_on_mystruct’ is negative
I admit it's not the most useful thing, because it only tells you the line number of the error. But it is the simplest, stand-alone, technique I can think of.
A more general macro is:
#define DUMB_STATIC_ASSERT(test) typedef char assertion_on_mystruct[( !!(test) )*2-1 ] DUMB_STATIC_ASSERT( sizeof(mystruct)==1024 ); DUMB_STATIC_ASSERT( sizeof(my_other_struct)==23 ); DUMB_STATIC_ASSERT( sizeof(minimum_size_struct) >= 23 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With