How can I explicitly disable alignment on defined variable in gcc?
Take this code:typedef struct{
unsigned long long offset;
开发者_开发百科unsigned long long size;
unsigned long type;
unsigned long acpi;
}memstruct;
memstruct *memstrx;
This would define an structure having a size of 24 bytes.
I tried doing:memstrx=(void*)(0x502);
So
&memstrx[0]
should have an value of 0x502
&memstrx[1]
, 0x51A
&memstrx[2]
, 0x532
... and so on and so forth.
But things doesn't seem to be right.
Instead, the
&memstrx[1]
, displays an address of 0x522
&memstrx[2]
, 0x542
&memstrx[3]
, 0x552
... and so on and so forth.
I suspect GCC has implicitly re-sized the structure to 32 bytes (from 24 bytes), forcing a (64-bit alignment of each entry). And I don't really want this behavior only for this structure. How should I tell GCC to not align that structure?
No it can't be done.
The minimal size of the structure you show is 8*4 = 32 bytes.
sizeof(unsigned long) = 8 on 64 bit architecture (Linux)
Edit: if you would use
-unsigned
instead of unsigned long
or
uint32_t
anduint64_t
instead ofunsigned long
andunsigned long long
you would get expected alignment.
#pragma pack(x) can change the structure alignment restrictions on both GCC and MSVC.
GCC uses the LP64 model for 64bit builds - which means longs and pointers are 64bits. You need to change to unsigned int for your 32bit fields, OR use and uint32_t and uint64_t for stable field sizes.
#pragma pack(1)
typedef struct{
unsigned long long offset;
unsigned long long size;
unsigned int type;
unsigned int acpi;
}memstruct;
#pragma pack()
here's one option to control alignment using gcc:
http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html
精彩评论