Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the size of struct w/o padding?

Tags:

c++

c

gcc

Lets assume I have a structure:

struct A {
  uint16_t a;
  uint64_t b;
};

is there a way to get the size of A w/o padding ? i.e.: The sum of sizeof of all the members (even if it is not recursive).

Normally sizeof(A) == 16. I would like __GCC_sizeof__(A) == 10.

I want it in a test code w/o affecting the actual code, which means no "#pragma"s and no "__attribute__" in the structure definition. (Though it can be done with #ifdef TEST, but it is very ugly).

It doesn't have to be portable, GCC is enough.

Thanks!

like image 770
Vadim S. Avatar asked Jan 17 '13 14:01

Vadim S.


1 Answers

I think sizeof(A::a) + sizeof(A::b) should do the trick for you. There's no way to get an unpadded size of a struct because what purpose could such a size serve a program?

like image 75
Mark B Avatar answered Oct 19 '22 15:10

Mark B