Define a packed version of a C structure

I have a C structure defined somewhere outside of my code. Can I define a packed version of the same structure? If I define my own structure from the start, it's easy:

struct test {
    // members
} __attribute__((packed));

      

I defined a simple structure and tried two possibilities:

struct test {
    int x;
    double y;
    char z;
};

struct test_p {
    struct test __attribute__((packed)) s;
};

      

and this:

struct test {
    int x;
    double y;
    char z;
};

struct test_p {
    struct test p;
} __attribute__((packed));

      

However, none of these work (both don't compile though) print sizeof (struct test_p) = 24 on my system (I'm using gcc 4.8.2 on a 64 bit machine) which is the same as sizeof (struct test). Is there a way to achieve the desired effect?

Just in case you're wondering: I want to parse packets received over the network that have just been packed. The point is that I cannot change the header file because it is part of a third-party library and the structure itself contains too many fields to copy them one by one. I can, of course, copy the structure definition into my own header and make a packaged version - actually this is the solution I'm currently using, but I'm just wondering if there is a more concise solution that doesn't involve copying the entire definition.

+3


source to share


1 answer


gcc has introduced __attribute__((packed))

precisely to avoid the dangerous effects you are looking for: the structure definition must be binary, compatible between all user applications and libraries that use the same definition.

But gcc also provides a way to do the old-fashioned, dangerous way - #pragma pack(push,n)

and #pragma pack(pop)

. It would only work reliably if the third party header file only contains the structure definition, or you don't use anything else from the header. Use them like this:



#pragma pack(push,1)
#include "theheader.h"
#pragma pack(pop)

      

Otherwise, I personally would just copy the structure definition, rename it, and add it __attribute__((packed))

to my own header. Packing with pragmas the entire header is really a dirty hack. And third-party titles can change unexpectedly, contributing to bit rot .

+1


source







All Articles