Home >Backend Development >C++ >Can C Structs Be Safely Read and Written Across Platforms and Compilers?
Question:
Is it possible to safely read/write a C struct to a file in a manner that ensures cross-platform and compiler compatibility?
Answer:
No, it is not possible due to the lack of binary-level standardization in C .
According to Don Box, C lacks standardization at the binary level, meaning that different compilers may implement struct padding differently. Even within the same compiler, the packing alignment for structs can vary depending on the pragma pack used.
Additionally, the order of members within a struct can affect its size. For instance, structs with identical members but different declaration orders can have different sizes.
Example:
struct A { char c; char d; int i; }; struct B { char c; int i; char d; };
Compiling the above code with gcc-4.3.4 produces:
8 12
This demonstrates that even though both structs have the same members, their sizes differ.
Conclusion:
The standard does not specify how padding should be implemented, leaving it up to the discretion of compilers. As a result, it is impossible to assume that all compilers will apply the same padding rules, making cross-platform compatibility difficult to achieve.
The above is the detailed content of Can C Structs Be Safely Read and Written Across Platforms and Compilers?. For more information, please follow other related articles on the PHP Chinese website!