Reputation: 187
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!
Upvotes: 8
Views: 4417
Reputation: 299810
The purpose is the ability to track newly added structure members from inside the test.
It would have been better had you ask this first...
And the answer is yes, there are ways, but not by #include
the file; you should use something that is able to get the AST/ABT structure and lists the fields then compare it against a pre-registered list. This is something possible with Clang, for example.
But now, let's go one step further. Why would you want to test that ? It's brittle!
It would be better to test functionality, what's hidden is hidden for a reason.
If each functionality is tested correctly, then it matters not whether you know the list of fields as long as the tests pass.
Upvotes: 3
Reputation: 2711
In C language, you can use a preprocessor directive #pragma
to check sizeof
structure without padding..
#pragma pack(1)
will give you the sizeof
structure without padding..
Upvotes: 0
Reputation: 96241
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?
Upvotes: 4
Reputation: 1167
I would look at this Stackoverflow response:
Is gcc's __attribute__((packed)) / #pragma pack unsafe?
and at this web site for the GCC information:
http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html
If you set the pragma before the structure to 1, it should align on byte boundaries and be a compact size so you can use sizeof to get the number of bytes.
If it is just with a small amount of structure, you can enable the pragma before the declaration of the structure and then disable it afterward.
Hopefully the about is helpful in your efforts.
Upvotes: 2