Anonymous
Anonymous

Reputation: 105

Structure member alignment in GCC

I'm porting an msvc project, which has several libraries and each library has specific structures member alignment. Using default alignment caused lots of fatal misalign problems and googling told me that I can solve this issue by setting alignment for each struct / class / union manually with the __attribute__ ((aligned (MY_ALIGN))) flag, however there is one thing that bothers me:

Let's say for simplicity sake that project A uses 1 byte alignment and project B, which actively uses project A's functionality and includes lots of its headers, has 16 bytes alignment. Would there be a problem with that, or am I thinkg too much and it would just work? I have a bad feeling that when building a library, msvc compiler sets alignment for each structs in all headers (no matter if they are included in a project or are referenced by sources). Is this true? And if it is, please tell me, how should I set the alignment to emulate MSVC's structure member alignment setting?

Upvotes: 2

Views: 3239

Answers (2)

unkulunkulu
unkulunkulu

Reputation: 11922

First of all, every header #include'd in your source file gets processes literally, it doesn't matter whether it in the same project or not.

It can definitely lead to some problems. For example, Project A defines a structure and aligns all its members to a byte boundary (packed) and exports a function accepting a pointer to this structure. Then if Project B for some reason is compiled in such an environment that the same structure gets aligned in a different way, it would make it impossible to pass an address of an instance of this struct directly to that exported routine. They have different sizeofs at least in A and B.

The simple rule is this:
1) if you're to be interfacing with some external compiled library, you should make sure that structure alignment is in agreement with that used by the library compiler. This concerns the structures present in library's headers. Good libraries try to minimize the effort by providing #pragma's for some compilers to ensure the proper alignment.
2) if you're using structures inside some project of yours you can leave it alone, just write portable code that doesn't rely upon some specific alignment, it will do.

Upvotes: 1

Jesus Ramos
Jesus Ramos

Reputation: 23266

I don't think there should be an issue with that. Just remeber that unaligned access (4 byte minimum I think on most systems) will cost you (although you save space albeit not much in some situations). The structures themselves have the attribute and the compiler will do all the pointer arithmetic so as long as the headers don't mess with each other's definitions it should be okay.

Upvotes: 1

Related Questions