3

GCC doc says:

You may only specify the packed attribute attribute on the definition of an enum, struct or union, not on a typedef that does not also define the enumerated type, structure or union.

Does it mean that I cannot apply this attribute for classes?

2 Answers2

2

I couldn't find the answer clearly in the GCC doc, but with the following experimentation, it seems that you can.

#include <iostream>


struct UnPackedStruct {
    unsigned char a;
    int b;
};

struct __attribute__ ((__packed__)) PackedStruct {
    unsigned char a;
    int b;
};

class __attribute__ ((__packed__)) PackedClass{
    unsigned char a;
    int b;
};

int main()
{
    std::cerr << "sizeof( UnPackedStruct ): " << sizeof(UnPackedStruct)
            << ", sizeof( PackedStruct ): " << sizeof(PackedStruct)
            << ", sizeof( PackedClass): " << sizeof(PackedClass)
            << "\n";

    return 0;
}

Output:

sizeof( UnPackedStruct ): 8, sizeof( PackedStruct ): 5, sizeof( PackedClass): 5

Try it with online compiler

mgagnon
  • 314
  • 1
  • 4
  • 10
1

The documentation for GCC 9.x was updated to include "class" in that list:

You may only specify the packed attribute on the definition of an enum, struct, union, or class, not on a typedef that does not also define the enumerated type, structure, union, or class.

So you can certainly apply that attribute to classes, at least as of GCC 9.x, but probably also in earlier versions.

pogojotz
  • 452
  • 5
  • 11