Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct alignment and portability across compilers

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.

like image 811
Roman L Avatar asked Apr 24 '12 12:04

Roman L


2 Answers

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.

like image 111
Havoc P Avatar answered Sep 21 '22 03:09

Havoc P


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.

like image 22
caf Avatar answered Sep 20 '22 03:09

caf