C struct alignment and portability across compilers

c, portability, windows

Solution

TL;DR in practice you should be fine.

The C standard does not define this but a platform ABI generally does. That is, for a given CPU architecture and operating system, there can be a definition for how C maps to assembly that allows different compilers to interoperate.

Struct alignment isn't the only thing that a platform ABI has to define, you also have function calling conventions and stuff like that.

C++ makes it even more complex and the ABI has to specify vtables, exceptions, name mangling, etc.

On Windows I think there are multiple C++ ABIs depending on compiler but C is mostly compatible across compilers. I could be wrong, not a Windows expert.

Some links:

- what is an ABI? http://gcc.gnu.org/ml/libstdc++/2001-11/msg00063.html

- things an ABI has to define C++ ABI issues list

- example C++ ABI spec http://sourcery.mentor.com/public/cxx-abi/abi.html

- how the ABI evolved on Solaris http://developers.sun.com/solaris/articles/CC_abi/CC_abi_content.html

Anyway the bottom line is that you're looking for your guarantee in the platform/compiler ABI spec, not the C standard.

Problem

Assuming the following header file corresponding to, for example, a shared library. The exported function takes a pointer to a custom structure defined in this header: ``` // lib.h typedef struct { char c; double d; int i; } A; DLL_EXPORT void f(A* p); ``` If the shared library is built using one compiler and then is used from C code built with another compiler it might not work because of a different memory alignment, as Memory alignment in C-structs suggests. So, is there a way to make my structure definition portable across different compilers on the same platform? I am interested specifically in Windows platform (apparently it does not have a well-defined ABI), though would be curious to learn about other platforms as well.

Original source

Related problems