TITLE: still more on portability and alignment (Private email, 30 Jun 98) SCHMIDT: "Robert H. Schmidt" > This is a quick note about your posting on comp.std.c++ concerning portable > determining alignment. As I recall, structure alignment/padding is > unspecified, implying vendors may use different alignment for different > objects (I believe the behavior is per-object and not per-type, although I > could be wrong). > > I wonder, then, if you can ever create a generic solution guaranteed to > work throughout a program. (Certainly the presence of different pragmas or > compiler switches can potentially make objects of a given struct type > byte-aligned in one translation unit and word-aligned in another.) TRIBBLE: david.tribble@central.beasys.com Yes, we rely on it where I work. You do have to be wary of compiler options and pragmas that can alter the alignment of structure members. As I mentioned in my post, even byte-aligned compilers sometimes word-align structure members for efficiency. On the other hand, just as you have to be wary of pragmas and options that alter member alignment, so does the compiler itself. Consider the declaration of the standard FILE structure in , a header file supplied by the compiler vendor, which might be something like this: struct FILE { unsigned char _flags; /* Flags for feof(), ferror() */ int _cnt; /* Remaining chars in _buf */ char * _buf; /* Buffer pointer */ ... }; Since the stdio library supplied by the vendor was presumably compiled using the same structure declaration as your code, its code assumes a particular alignment for the members of 'FILE'. (Note that member '_cnt' might or might not be preceded by one or more padding bytes, depending on its alignment.) In order for the library to operate correctly on objects of type 'FILE', the compiler must always assume the same member alignment for 'FILE', regardless of any compiler options specified by the user when compiling his code. So, presumably, the struct declaration would be defined in such a way as to force one, and only one, alignment, perhaps with a declaration like this: #pragma align(4) /* Force word alignment */ struct FILE { ... }; The same situation exists for compilers for a particular platform and O/S but from different compiler vendors. Code that makes calls to the underlying O/S that passes structure arguments must ensure that its alignment of structure members agrees with the alignment expected by the O/S function. (Consider calling the Win32 API functions from code compiled by Microsoft, Borland, Symantec, Watcom, etc.) So structure member alignment must, to some degree at some level, be the same even for different compiler vendors.