Reputation: 2423
struct my_struct
{
char a;
short b;
int c;
};
sizeof(my_struct)
may vary on different machines (size of any standard c++ type may vary in particular). It depends from memory alignment as well (#pragma pack(*)
etc.). What would be the best way of implementing fixed size struct?
Upvotes: 3
Views: 4522
Reputation: 101456
If you can be somewhat realistic and knowledgeable about your target platforms, you can fairly easily find some common ground and use that as the basis for your structures.
For example, if your target platforms are Windows and Linux running on current x86 hardware, then you know a few things already:
char
is exactly 1 byte per the Standardint8_t
and uint8_t
are exactly 8 bits under C++11 (most C++03 compilers provide these anyway)int16_t
and uint16_t
are exactly 16 bits under C++11int32_t
and uint32_t
are exactly 32 bits under C++11int64_t
and uint64_t
are exactly 64 bits under C++11char
arraysEndianness will still be an issue, so you will have to deal with this when converting multi-byte types.
Trying to devise a structure which will be guaranteed by the Standard to have the same binary representation on the wire on all exotic platforms is impossible. You can get close by using only char
s, but even then there is no guarantee because you don't know how many bits are in a byte.
You could try to use bitfields to represent your data, but you still don't know how many bits are in a byte so you can't be certian how much padding will be added at the end.
Portability serves a purpose: portable code is easier to maintain and extend than platform-specific code. Pursuing portability for portability's sake is an academic goal that has no place in professional programming. Pursuing portability for maintainability's sake on the other hand is a laudable goal, but it's also a balancing act. If you come up with a completely portable solution that is works on all possible platforms, but you will only run on two of those platforms and your code is impossible to maintain, then what is the point?
Upvotes: 2
Reputation: 139
You could pack your structure to have a deterministic size. Here is a link to implement that in a portable way: Visual C++ equivalent of GCC's __attribute__ ((__packed__))
Upvotes: 1
Reputation: 490128
Nothing you can do will guarantee that a struct will have the same size on all possible implementations. About the closest you can probably get would be something like:
struct my_struct {
char contents[some_size];
};
This at least guarantees that the contents
will be the same size on all implementations. The implementation is still free to insert padding after the contents
though, so you could still get different sizes on different implementations.
Upvotes: 2