In c++, is there any way to guarantee that a long is 4 bytes? Perhaps a compiler flag for g++?
We are reusing some windows code in a linux program, and in windows a long is 4 bytes, but on my linux machine a long is 8 bytes. We can't go and change all the longs to ints because that would break the windows code.
The reason I need to guarantee longs are 4 bytes is because in certain parts of the code, we have a union of a struct and a char array, and when compiling for 64bit linux, the char array does not line up with the other struct.
Here are some code snippits for clarification:
struct ABC {
unsigned long data1;
unsigned short data2;
unsigned short data3;
unsigned char data4[8];
};
//sizeof(ABC) (32 bit): 16, sizeof(ABC) (64 bit): 24
union ABC_U {
ABC abc;
unsigned char bytes[16];
};
EDIT:
I forgot to mention, this problem only came up when trying to compile for 64 bit. Windows seems to like to keep longs 4 bytes regardless of architecture, whereas linux g++ usually makes longs the same size as pointers.
I'm leaning towards using a uint32_t here because this particular structure isn't used in the Windows code, and that wouldn't affect the program globally. Hopefully there aren't any other sections of the code where this will be a problem.
I found the compiler flag -mlong32, but this also forces pointers to be 32 bits which is undesirable, and as it forces nonstandard behavior would likely break the ABI like PascalCuoq mentioned.