Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual C++ equivalent of GCC's __attribute__ ((__packed__))

For some compilers, there is a packing specifier for structs, for example ::

 RealView ARM compiler has "__packed" Gnu C Compiler has "__attribute__ ((__packed__))" Visual C++ has no equivalent, it only has the "#pragma pack(1)" 

I need something that I can put into the struct definition.

Any info/hack/suggestion ? TIA...

like image 877
Malkocoglu Avatar asked Oct 08 '09 13:10

Malkocoglu


People also ask

What is __ attribute __ packed in C?

4.11 The __packed__ Attribute This attribute, attached to struct or union type definition, specifies that each member (other than zero-width bitfields) of the structure or union is placed to minimize the memory required. When attached to an enum definition, it indicates that the smallest integral type should be used.

What is Pragma pack in C++?

The #pragma pack directive modifies the current alignment rule for only the members of structures whose declarations follow the directive. It does not affect the alignment of the structure directly, but by affecting the alignment of the members of the structure, it may affect the alignment of the overall structure.


2 Answers

You can define PACK like as follows for GNU GCC and MSVC:

#ifdef __GNUC__ #define PACK( __Declaration__ ) __Declaration__ __attribute__((__packed__)) #endif  #ifdef _MSC_VER #define PACK( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop)) #endif 

And use it like this:

PACK(struct myStruct {     int a;     int b; }); 
like image 84
Steph Avatar answered Oct 12 '22 10:10

Steph


I don't know a slick way of doing it, but you could possibly do something horrible like this:

#include "packed.h" struct Foo { /* members go here */ } PACKED; #include "endpacked.h" 

Then for MSVC, packed.h:

#define PACKED #pragma pack(push,1) 

endpacked.h

#pragma pack(pop) #undef PACKED 

For gcc, packed.h:

#define PACKED __attribute__ ((__packed__)) 

endpacked.h:

#undef PACKED 

Fundamentally, packing is too platform-dependent. Suppose your packed struct has 8-bit fields in it, and consider some system with a 16-bit byte. It can't have a struct representing your data just by packing - you'd have to know how 8-bit bytes are converted to 16-bit bytes when transferred between the two systems. The struct on the 16bit machine might need bitfields, in which case you'd have to know how the implementation lays them out.

So if the code is intended to be generally portable, you may just have to define whatever packed structures you need in a platform-specific section of your header file. Or rather, structure your code so that a future port can do that if it has to.

like image 37
Steve Jessop Avatar answered Oct 12 '22 10:10

Steve Jessop