When designing a C interface, it is common to let into the public interface (.h
) only what needs to be known by the user program.
Hence for example, the inner components of structures should remain hidden if the user program does not need to know them. This is indeed good practice, as the content and behavior of the struct could change in the future, without affecting the interface.
A great way to achieve that objective is to use incomplete types.
typedef struct foo opaqueType;
Now an interface using only pointers to opaqueType
can be built, without the user program ever needing to know the inner working of struct foo
.
But sometimes, it can be required to allocate such structure statically, typically on stack, for performance and memory fragmentation issues. Obviously, with above construction, opaqueType
is incomplete, so its size is unknown, so it cannot be statically allocated.
A work around is to allocate a "shell type", such as :
typedef struct { int faketable[8]; } opaqueType;
Above construction enforces a size and an alignment, but doesn't go farther into describing what the structure really contains. So it matches the objective of keeping the type "opaque".
It mostly works. But in one circumstance (GCC 4.4), the compiler complains that it breaks strict-aliasing, and it generates buggy binary.
Now, I've read a ton of things about strict aliasing, so I guess I understand now what it means.
The question is : is there a way to define an opaque type which can nonetheless be allocated on stack, and without breaking strict aliasing rule ?
Note that I've attempted the union method described in this excellent article but it still generates the same warning.
Note also that visual, clang and gcc 4.6 and later don't complain and work fine with this construction.
[Edit] Information complement :
According to tests, the problem only happens in the following circumstances :
- Private and public type different. I'm casting the public type to private inside the
.c
file. It doesn't matter apparently if they are part of the same union. It doesn't matter if the public type containschar
. - If all operations on private type are just reads, there's no problem. Only writes cause problems.
- I also suspect that only functions which are automatically inlined get into trouble.
- Problem only happens on gcc 4.4 at -O3 setting. -O2 is fine.
Finally, my target is C90. Maybe C99 if there really is no choice.
int
for the fake type; usechar
. Doesn't that avoid the strict aliassing issues? – Wittenburgint
is required for the alignment. (It could besize_t
,short
orlong long
depending on necessary alignment).char
does not provide such guarantee, the structure could start at any position in memory. But maybe Rodrigo answer (a union) is the right one. – Besides