سؤال

I am working on a network packet simulator in C which requires the use of several different struct definitions, for instance:

struct DMPacketStruct
{
   short int header[8];
   short int a;
   unsigned char b;
   short int c;
}DMPacket;

By default, the compiler (Intel) would add buffers after b and c, so I could either use the #pragma pack pre-processor command or add -fpack-struct to the compiler flags. Since I have several similar structures in the program, I would like to use -fpack-struct. Other than slowing down my IO some, are there any drawbacks to using the flag instead of the pre-processor command?

هل كانت مفيدة؟

المحلول

The #pragma is part of the source code and helps to document the actual structure's layout. If it were in a Makefile or compiler option external, it is far from obvious by reading the code what the layout is.

If need be, other compilers can exactly support it with conditional pragmas. As it turns out, #pragma pack() is supported by Borland, gcc, and VC. Maybe even Intel:

#if defined(__INTELC_) || defined(__BORLANDC__) || defined(__MSVC__)
 #pragma pack(1)
#elif  defined(__SOME_OTHER_C__)
 #pragma struct packing(0)
...
#endif

نصائح أخرى

There is not in this case. But you have to keep in mind that both those options are compiler-specific. As far as I am aware gcc also supports -fpack-struct, but I have never seen that pragma in gcc code. clang has not documented -fpack-struct. You could now start listing a lot of different compilers and how their mechanisms for packing work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top