No, there's no way... you only have sizeof()
, and you need to take care of the padding...
Find packed size of a structure
Question
Is there a way to find the packed size of a structure defined and declared without packed attribute in GCC compiler?
Example:
struct Name
{
int a;
char ch;
}
any function or macro like get_packed_size(Name)
should return 5
Solution 2
OTHER TIPS
Define your struct using a macro that provides the required information. For example (though there are other possible implementations):
#define DEFINE_STRUCT_WITH_KNOWN_PACKED_SIZE(StructName, StructBody)\
struct StructName StructBody\
struct __attribute__ ((__packed__)) StructName##_packed StructBody
#define GET_PACKED_SIZE(StructName) sizeof (struct StructName##_packed)
DEFINE_STRUCT_WITH_KNOWN_PACKED_SIZE(Name, {
int a;
char ch;
};)
#include <stdio.h>
int main() {
printf("%lu", GET_PACKED_SIZE(Name));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow