user13826843
user13826843

Reputation:

Is __attribute__((packed)) GCC only, or cross platform?

Is __attribute__((packed)) GCC only, or cross platform?

If it's GCC only, how can I check if I am compiling on GCC?

So I can do this for a cross-platform packed structure:

#if /*COMPILING_ON_GCC*/
#   define Packed __attribute__((packed))
#else
#   define Packed
#endif

struct MyStruct {
    char A;
    int B;
    long C;
    //...
} Packed;

If it's GCC, Packed will be replaced with __attribute__((packed)), and if it's not, it will be replaced with nothing, and not cause any problems.

BTW I LOVE POUND DEFINE MACROS!!!

Upvotes: 0

Views: 917

Answers (2)

0___________
0___________

Reputation: 67602

No attributes or pragmas are cross platform. They are a compiler extension and have to be avoided in the portable code.

So I can do this for a cross-platform packed structure:

If you do not care about the packing, so why are you going to use it. Remember that packing comes with serious performance penalty on many platforms.

Upvotes: 1

Nate Eldredge
Nate Eldredge

Reputation: 58193

It's supported by gcc and clang, but it's not part of the C standard and other compilers will not necessarily support it. For instance, MSVC does not.

Other compilers may provide similar functionality using different syntax, e.g. #pragma pack. But there is no one way to do it that will work everywhere.

You can try some examples on godbolt.

You can determine whether you're compiling with gcc by testing if the __GNUC__ macro is defined. See https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html#Common-Predefined-Macros

#ifdef __GNUC__
#define Packed __attribute__((packed));
#else
#define Packed /* nothing */
#endif

Upvotes: 2

Related Questions