Compiling C Code with Anonymous Structs/Unions
The question arises regarding how to compile C code with anonymous structs or unions, as demonstrated in C with anonymous fields using unions. In C, an attempt to create a similar structure using named structs containing an anonymous union results in compilation errors.
The error messages indicate that the anonymous union and struct fields are not declared within the struct declaration. To enable this feature in C, it is necessary to use the -fms-extensions compiler flag.
Revised Code with -fms-extensions
<code class="c">#include <stdio.h> #include <assert.h> typedef struct { union { float x, y, z; } xyz; } Vector3; int main() { Vector3 v; assert(&v.xyz.x == &v.x); assert(&v.xyz.y == &v.y); assert(&v.xyz.z == &v.z); return 0; }</code>
With this modification, the code will compile successfully, and the assertions will pass, confirming that the addresses of the union members and the struct fields are equivalent.
The above is the detailed content of How Can I Compile C Code with Anonymous Structs or Unions?. For more information, please follow other related articles on the PHP Chinese website!