what is the difference between __attribute__((__packed__)); and #pragma pack(1)
Asked Answered
S

1

6

I am porting a code which runs perfectly on Linux to windows visual c++. I have this code in Linux:

struct exif_desc
{
    uint16_t  tag;
    uint16_t  type;
    uint32_t  length;
    uint32_t  value;
}
__attribute__((__packed__));

I am getting error on windows:

'__packed__' : undeclared identifier 

I am wondering if I can fix this error by using

#pragma pack(1)

is there any difference between them? Is there any syntax that can be used in Linux and Windows for this attribute?

Sprout answered 25/8, 2015 at 16:2 Comment(2)
From my understanding these should be the same. Don't forget to reset the alignment again with #pragma pack() at the end of the struct. Question might be duplicate of #1538464Classicist
Possible duplicate of What are the differences between #pragma pack(push, n)/#pragma pack(pop) and __attribute__((__packed__, aligned(n) )) on GCC?Approbation
R
3

__attribute__ is a GCC extension, specific to GCC (and other compilers which attempts to be compatible with GCC).

#pragma pack is originally a Visual C++ compiler specific extension. It has, as noted by commenters, been implemented in GCC as well for VC++ compatibility.

Normally you can't use extensions in one compiler in another compiler. Case in point: __attribute__ doesn't exist as an extension in the Visual C++ compiler.

Rampageous answered 25/8, 2015 at 16:6 Comment(3)
#pragma pack can be used in gcc too (gcc.gnu.org/onlinedocs/gcc/Structure-Packing-Pragmas.html)Sprout
#pragma pack is nonstandard extension, but woks with most compilersNullipore
Note also that #pragma pack takes effect from the point of definition and until another #pragma pack, while __attribute__((__packed__)) is effective only for the definition it's attached to. This is important.Equanimity

© 2022 - 2024 — McMap. All rights reserved.