Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#pragma pack() with push and pop vs unpack

Tags:

c

pragma

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
like image 660
liv2hak Avatar asked Sep 16 '15 08:09

liv2hak


1 Answers

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.

like image 108
Stas Avatar answered Oct 26 '22 05:10

Stas