Similar question, but specific to packed structs: Why would the size of a packed structure be different on Linux and Windows when using gcc?
I'm building a shared library for Linux and Windows that needs to deal with well-structured data over a network connection. I'm using gcc 4.8.2 on Linux, and cross-compiling for Windows targets using i686-pc-mingw32-gcc 4.8.1.
I've made this little program to demonstrate the issue (note the GCC attributes are commented out, left them in for reference):
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
typedef uint16_t word_t;
typedef enum //__attribute__((__packed__))
{
PRIO_0 = 0,
PRIO_1,
PRIO_2,
PRIO_3,
PRIO_4,
PRIO_5,
PRIO_6,
PRIO_7,
}
prio_t;
typedef enum //__attribute__((__packed__))
{
FLAG_A = 0,
FLAG_B,
}
flag_t;
typedef struct //__attribute__((__packed__))
{
word_t id : 8;
prio_t prio : 3;
flag_t flag_1 : 1;
flag_t flag_2 : 1;
flag_t flag_3 : 1;
flag_t flag_4 : 1;
word_t spare : 1;
}
recd_t;
int main(int argc, char *argv[])
{
#define NAME_WIDTH 32
printf("%-*s = %lu\n", NAME_WIDTH, "sizeof(prio_t)", (unsigned long)sizeof(prio_t));
printf("%-*s = %lu\n", NAME_WIDTH, "sizeof(flag_t)", (unsigned long)sizeof(flag_t));
printf("%-*s = %lu\n", NAME_WIDTH, "sizeof(recd_t)", (unsigned long)sizeof(recd_t));
return 0;
}
I'm compiling for Linux using:
gcc -g -Wall test.c -o ./test
And Windows:
i686-pc-mingw32-gcc -g -Wall test.c -o ./test.exe
Very straightforward I thought. When run on Linux, the output is what I would expect:
sizeof(prio_t) = 4
sizeof(flag_t) = 4
sizeof(recd_t) = 4
But on Windows:
sizeof(prio_t) = 4
sizeof(flag_t) = 4
sizeof(recd_t) = 12
So what's the deal with the Windows sizes? Why are they different from Linux in this case?
I will eventually need to pack these enums and structs, but this issue appears before any packing is done. When enabled though, the results are similar:
Linux:
sizeof(prio_t) = 1
sizeof(flag_t) = 1
sizeof(recd_t) = 2
Windows:
sizeof(prio_t) = 1
sizeof(flag_t) = 1
sizeof(recd_t) = 6