C struct alignment and portability across compilers C struct alignment and portability across compilers windows windows

C struct alignment and portability across compilers


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:

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


The only way to know for sure is to consult the documentation of the compilers in question. However, it is usually the case that C struct layout (except, as you say, for bitfields) is defined by an ABI description for the environment you're using, and C compilers will tend to follow the native ABI.


Not only that it is not guarantied, but even if you use the same compiler there might be differences due to different compiler switches used in the build, or if you use different versions of the same compiler and same switches (happened in an embedded compiler I worked on).

You need to make make sure the structs are represented exactly the same, use switches, #pragmas, whatever the compilers gives you.

My advice - to stay way from this altogether. Pass your arguments in the function, not wrapped within a struct.

And even in this simple form, if you deal with two compilers, it's not trivial. You need to make sure that an int takes the same number of bytes, for example. Also calling conevntion - arguments order - from left to right or from right to left - can differ between compiler.