[Qt-interest] Portable way to get compiler's memory alignment

Thiago Macieira thiago at kde.org
Thu Mar 25 08:18:24 CET 2010


Em Quinta-feira 25. Março 2010, às 06.27.53, Nikos Chantziaras escreveu:
> Is there some portable method, trick, hack, etc, to get the compiler's
> memory alignment?  I'm currently simply assuming 4 byte alignment, which
> seems to work for 32-bit as well as 64-bit GCC.  Aligning a size to
> 4-byte worst-case is currently done with:
> 
>    (size + 3) & ~3
> 
> but I suspect this will be wrong on some systems.  Can Qt be of
> assistance here?  If not, what do you guys recommend?

There's a macro in qglobal.h called Q_ALIGNOF, which you can use to get a 
type's alignment. It's not defined for all compilers, so you need to #ifdef 
around it.

C and C++ rule that the alignment of a primitive type is its natural alignment 
for the platform, while the alignment of aggregate types is the alignment of 
the most-strictly aligned type contained within the aggregation. That means 
you need to know the platform ABI to know how items are aligned.

In most recent architectures, you can assume that no type is more strictly 
aligned than the machine word. So:

alignof(char) == 1
alignof(short) == 2
alignof(int) == 4
alignof(void*) == sizeof(void*)
alignof(long long) == alignof(void*)

However, there are some extended "primitive" types that break that rule, like 
streaming types meant for streaming assembly instructions, that have 128- and 
256-bit alignment requirements on x86.
-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Senior Product Manager - Nokia, Qt Development Frameworks
      PGP/GPG: 0x6EF45358; fingerprint:
      E067 918B B660 DBD1 105C  966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100325/e6387034/attachment.bin 


More information about the Qt-interest-old mailing list