LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   When should I use pragma pack? (https://www.linuxquestions.org/questions/programming-9/when-should-i-use-pragma-pack-882223/)

PinoyAko 05-23-2011 05:27 AM

When should I use pragma pack?
 
When should I use pragma pack?

I found this code on some source files while other sources do not have the pragma pack()
Code:

#pragma pack (1)
typedef struct _net_ip_header_t {
        uint8 hdr_len:4;                // header length
        uint8 version:4;                // version
        uint8 tos;                                // type of service
        uint16 tot_len;                        // total length
        uint16 id;                                // identification
        uint16 flags_offset;        // fragment offset field
        uint8 ttl;                                // time to live
        uint8 proto;                        // protocol
        uint16 cksum;                        // checksum
        ip_addr src_ip;                        // source ip address
        ip_addr dst_ip;                        // destination ip address
} net_ip_header_t;
#pragma pack ()


dwhitney67 05-23-2011 05:31 AM

The use of pragma pack is to ensure that the data structure is byte-aligned versus word-aligned. For example, the following struct takes up 8 bytes (perhaps not on all systems), but on typical Linux machines:
Code:

struct Foo
{
  int  val;  /* takes up 4 bytes */
  char ch;    /* takes up 1 byte  */
};

/* Yet struct Foo takes up 8 bytes */

With the pragma pack directive, the struct above will only take up 5-bytes.


All times are GMT -5. The time now is 10:39 PM.