Thread: When should I use pragma pack?

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    5

    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 ()

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > When should I use pragma pack?
    If you want to write portable code - never.

    It might get you out of a hole, if the only issue is padding and alignment, but it can never be a fix for endian differences.

    Also, over-use of pack() leads to poor performing code which has to suffer the inefficient memory accesses that result from accessing mis-aligned data when there was no need for the mis-alignment to begin with.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Use it as infrequently as possible. Only when the alternative would be a lot of manual bit manipulation.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. please solve my #pragma pack problam
    By nkrao123@gmail. in forum C Programming
    Replies: 2
    Last Post: 10-10-2009, 03:22 AM
  2. #pragma pack(push,bitmap_data,1) ?
    By te5la in forum C++ Programming
    Replies: 3
    Last Post: 10-07-2008, 03:38 PM
  3. #pragma pack(1) workaround?
    By l3iggs in forum C Programming
    Replies: 5
    Last Post: 06-02-2008, 11:17 AM
  4. Replies: 1
    Last Post: 06-03-2005, 01:03 AM
  5. Structure Padding, pragma pack...
    By P.Phant in forum C Programming
    Replies: 4
    Last Post: 06-04-2003, 05:56 AM