0

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

lethal-guitar
  • 4,438
  • 1
  • 20
  • 40
Dinesh
  • 1,825
  • 5
  • 31
  • 40

2 Answers2

2

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));
}
Mankarse
  • 39,818
  • 11
  • 97
  • 141
0

No, there's no way... you only have sizeof(), and you need to take care of the padding...

Wagner Patriota
  • 5,494
  • 26
  • 49