__declspec(align(N))

Started by
4 comments, last by Silly_con 20 years, 5 months ago
where must be used align, in structs, functions or both ? and how do you get what is the apropiated value for a determinated proccessor, is based on cache, bus memory bandwitch ... ?
Advertisement
The only real reason to specify alignment that I can think of is for structures related to files and network protocols. Generally, the compiler knows what is better for the computer''s cache etc and thus you should trust it to size things properly. When using structures for file and network protocols, however, you generally want to save space. By setting alignment to 1 byte, you can tell the compiler that you don''t want any kind of padding and thus each field will only take the space it needs.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
SIMD instructions such as SSE is another reason to align. You can use a faster form if your data is aligned on a 16 byte boundary.

Some non-x86 CPUs also require any WORD/DWORD accesses to be aligned to an even address.

Structs are the usual place to align. Whether you need to align automatic "local" variables within function depends on the compiler you''re using.

The compiler generally determines the basics, plus if you''re writing (say) SSE code, you''ll know from the Intel manuals that 16byte alignment is good.

--
Simon O''Connor
3D Game Programmer &
Microsoft DirectX MVP

Simon O'Connor | Technical Director (Newcastle) Lockwood Publishing | LinkedIn | Personal site

I''m not familiar with __declspec(align(N)) syntax, I''ve usually seen alignment directives indicated by packing pragmas.

Alignments changes are usually temporary - specific to a particular structure in a file and not to the entire file. It''s not just SIMD instructions that need alignment. In some cases ordinary instructions in opcode form require explicit alignment adjustments, for example, setting window thunking code to 1 byte alignment instead of 8 byte or 16 byte.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
LessBread:


Packing pragmas serve a slightly different but related purpose (there are cases where you''d use BOTH at the same time):


__declspec(align()) determines the alignment of the START address of a piece of global data.

#pragma pack() determines the packing/padding bytes added at the END of a structure in memory.


Another example which requires alignment is when using memory mapped files - you need to align your offsets to the page size granularity.

--
Simon O''Connor
3D Game Programmer &
Microsoft DirectX MVP

Simon O'Connor | Technical Director (Newcastle) Lockwood Publishing | LinkedIn | Personal site

a SSE function would be aligned to 16 with __declspec(align(16)) or is only for variables inside the function?

This topic is closed to new replies.

Advertisement