What is `#pragma pack` for in network programming?

816 Views Asked by At
 #pragma pack(push)
 #pragma pack(1)

I downloaded a tutorial and it has these lines in the header file. I will appreciate if you guys can provide me any tutorials or references related to this.

3

There are 3 best solutions below

2
On BEST ANSWER

Microsoft's explanation:

http://msdn.microsoft.com/en-us/library/aa273913(v=vs.60).aspx

IBM's AIX xlC explanation:

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Fcompiler%2Fref%2Frnpgpack.htm

Basically, it determines the byte boundaries that will be used when storing a structure or union. The push/pop acts as a way to store and retrieve these settings on a stack.

For future reference, you might save yourself some time by searching for the keywords you're asking as about on the web. All I did to find this information was search for "pragma pack" at http://www.google.com

0
On

It's the MSVC++ specific packing specifier. You can find out exactly what it does from the documentation.

The packing changes how much padding the compiler is allowed to insert between data members of a given struct (or class) to maintain alignment. In the case of networking code, the #pragma pack specifier is probably being used so that a structure can be cast to a char* or void* to be passed to some network API, to send the entire struct over the network at once.

(Note this is unsafe as different machines have different rules for alignment and byte order; this will only work if both machines on each end of the wire use the same hardware type)

0
On

All #pragma statements are vendor specific.

This one is Microsoft specific, and describes how much "packing" (in bytes) the compiler can add to structs for better alignment.

The #pragma pack(push) simply saves and previous setting in a stack. You can then change the packing conditions for a certain block of code, and later on #pragma pack(pop) to restore the previous settings.