title: Define a packed version of a C struct
body: <p>I have a C structure defined somewhere outside my code. Can I define a packed version of the same structure? If I define my own structure from the start, that is easy:</p>
  
  <pre><code>struct test {
      // members
  } __attribute__((packed));
  </code></pre>
  
  <p>I defined a simple structure and tried two possibilities, this:</p>
  
  <pre><code>struct test {
      int x;
      double y;
      char z;
  };
  
  struct test_p {
      struct test __attribute__((packed)) s;
  };
  </code></pre>
  
  <p>and this:</p>
  
  <pre><code>struct test {
      int x;
      double y;
      char z;
  };
  
  struct test_p {
      struct test p;
  } __attribute__((packed));
  </code></pre>
  
  <p>However, neither of these work (both compile fine though) printing sizeof(struct test_p)=24 on my system (I use 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?</p>
  
  <p>Just in case you were wondering: I want to parse packets received over network which are just packed structures. The thing is, I can't modify the header file because it is a part of a third-party library, and the structure itself contains too many fields to copy them one by one. I can certainly copy the structure definition to my own header and make the packed version -- actually it is the solution I'm using now -- but I was just wondering if there is a more concise solution which does not involve copying the whole definition.</p>