Search code examples
cstructtypedef

How to use a typedef tagless struct with a struct tag?


I'm using the libbson C library to work with MongoDB. In this library, every defined struct is tagless with a typedef alias, e.g. the bson_t struct:

typedef struct {
   uint32_t flags;       /* Internal flags for the bson_t. */
   uint32_t len;         /* Length of BSON data. */
   uint8_t padding[120]; /* Padding for stack allocation. */
} bson_t

I would like to use all my struct types by explicitly typing struct name, so in this case, it would be struct bson_t. It's just personal preference, no offence for everyone.

If the library had defined the above using typedef struct bson_t { ... } bson_t it would have been possible, but as of now, the only way I have to use the bson_t type is without the struct prefix.

Is there anything that I can do to make the struct bson_t refer to the bson_t type? Besides editing the mongoc.h file, that is.

Thanks!


Solution

  • C 2018 6.7.2.3 5 says:

    … Each declaration of a structure, union, or enumerated type which does not include a tag declares a distinct type.

    and:

    Two declarations of structure, union, or enumerated types which are in different scopes or use different tags declare distinct types…

    So any declaration of a structure with a tag declares a distinct type from any structure without a tag. The C standard does not provide any way to make them the same type.