1

header1.h

#pragma pack(4)

header2.h

#include <iostream>

struct my_struct
{
  unsigned int a;
  double b;
};

__forceinline void show_h(my_struct* my_struct_ptr)
{
  std::cout << sizeof(my_struct) << '\t' << my_struct_ptr->b << '\n';
}

void show_cpp(my_struct*);

header2.cpp

#include "header2.h"

void show_cpp(my_struct* my_struct_ptr)
{
  std::cout << sizeof(my_struct) << '\t' << my_struct_ptr->b << '\n';
}

main.cpp

#include "header1.h"
#include "header2.h"
#include <iostream>

int main()
{
  my_struct my_struct;
  my_struct.b = 4.56;
  std::cout << sizeof(my_struct) << '\t' << my_struct.b << '\n';
  show_h(&my_struct);
  show_cpp(&my_struct);
  return 0;
}

main.cpp, header2.h and header2.cpp sees my_struct differently. Seems like it's about #pragma pack(4) which is defined in header1.h. Why it's affecting header2.h and main.cpp but not header2.cpp?

output

12 4.56
12 4.56
16 -9.25596e+061
Ivars
  • 2,375
  • 7
  • 22
  • 31
  • 1
    You've already answered your own question - you need to apply the same `pragma pack` to all modules that share the same headers - so add `#include "header1.h"` to header2.h. – Paul R Jan 31 '14 at 07:42
  • 1
    Why're you not including `header1.h` in `header2.cpp`? It's for such reasons usually the packing is done just above the struct itself instead of having it separate. – legends2k Jan 31 '14 at 07:43
  • @legends2k no, i don't. those are totally different standalone projects. – Ivars Jan 31 '14 at 07:44
  • @PaulR header2.h doesn't use header1.h – Ivars Jan 31 '14 at 07:47
  • Well, either add that or move the packing pragmas to the `struct`. – legends2k Jan 31 '14 at 07:48
  • It *does* use header1.h if it relies on the `#pragma pack`. Alternatively get rid of the `#pragma pack` entirely (why do you need it anyway ???), or put it somewhere more sensible. – Paul R Jan 31 '14 at 07:48
  • @PaulR i don't understand. how can header2.h use header1.h since it is including only ? it would be great if you could tell what's relly going on when i start compiling project. – Ivars Jan 31 '14 at 07:51
  • 1
    @Ivars: All he's saying it that it _should_ ideally be using it, since you're placing related entities in different headers, which is incorrect. So you can edit and make it use it. Or move them all to a single file and be done with it. – legends2k Jan 31 '14 at 07:53

1 Answers1

2

Get rid of header1.h and do

#pragma pack(push, 4)
struct my_struct
{
  unsigned int a;
  double b;
};
#pragma pack(pop)

Without this, having the packing done via a separate header will lead to confusions, when it's added in one TU while not in another TU.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222
  • 1
    Welcome. For details on the push and pop, see [here](http://msdn.microsoft.com/en-us/library/d9x1s805%28v=vs.110%29.aspx). – legends2k Jan 31 '14 at 08:00