0Day Forums
#pragma pack() with push and pop vs unpack - Printable Version

+- 0Day Forums (https://0day.red)
+-- Forum: Coding (https://0day.red/Forum-Coding)
+--- Forum: C & C++ (https://0day.red/Forum-C-C)
+--- Thread: #pragma pack() with push and pop vs unpack (/Thread-pragma-pack-with-push-and-pop-vs-unpack)



#pragma pack() with push and pop vs unpack - dimorphism746 - 07-26-2023

I have this sample program below

#include <stdio.h>
#include <stdlib.h>

#pragma pack(push)
#pragma pack(1)
typedef struct{
char a;
int b;
char c;
}st_a;
#pragma pack(pop)

typedef struct{
char a;
int b;
char c;
}st_b;


int main()
{
printf("size of struct a %zd \n",sizeof(st_a));
printf("size of struct b %zd \n",sizeof(st_b));

return 0;
}

Output of the above program is

size of struct a 6
size of struct b 12


Now if I change the struct declaration as below:


#pragma pack(1)
typedef struct{
char a;
int b;
char c;
}st_a;
#pragma unpack()

Output of the program is

size of struct a 6
size of struct b 6

Why is this difference in the behaviour? My understanding was that both structure declarations are doing the same thing.

I am running this on my MBP.

$gcc --version

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.4.0
Thread model: posix




RE: #pragma pack() with push and pop vs unpack - sifts687019 - 07-26-2023

Your compiler knows nothing about `unpack()` pragma, and just ignores it, so the same packing rules are applied to both structures.

`MSVC` compiler will issue a warning about unknown `#pragma` directives on first warning level.

Both `GCC` and `Clang` keep silence by default. You need to use `-Wunknown-pragmas` flag.