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
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.