C / C++ memory layout and optimization, problem with type punning, loading and saving.
I have some data as static class members. I use `__attribute__((__packed__))` for some classes and structs. I use type punning to convert between types that I believe have the same memory layout, but different signatures (members of different translation units). It works. I assume the sequence and offsets of members is as in my class / struct definition. Knowing this I just save and load memory regions to and from files and it works.
Until I enable any optimization in the compiler. I noticed that when my configuration file was written by the debug version, it does not load in release version. The first member is loaded correctly, the subsequent ones are not.
My only guess here it can be related to a different memory layout using -O1 .. -O3. Can `__attribute__((__packed__))` be ignored when optimizations enabled? Is there a way to express in my code I want a specific memory layout for a structure?
When I have a class that has only static members, is it equivalent of a C struct in memory? When the class is marked with the attribute, does it affect its static members? Is it a way to ensure specific members are always put in specific relative memory locations?
Consider the code:
#include "stdint.h"
class __attribute__((__packed__)) X
{
public:
static uint8_t a;
static uint16_t b;
static uint32_t c;
};
uint8_t X:a;
uint16_t X:b;
uint32_t X:c;
struct __attribute__((__packed__)) Y
{
uint8_t a;
uint16_t b;
uint32_t c;
};
int main(void)
{
Y s;
s.a = 1;
s.b = 2;
s.c = 3;
memcpy((void*)X.a, &s, sizeof(Y));
bool ok = s.a == X.a && s.b == X.b && s.c == X.c;
}When compiled with -O0, the `ok` is true. When compiled with -O1 - the `ok` is false.
What am I missing here?
