When trying to discover something in the code of some open source C projects, I often see this kind of typedef:
typedef struct _StructA StructA;
typedef struct _LinusTorvalds LinusTorvalds;
Why not directly define and use StructA, just StructA, instead of defining _StructA then “typedef” it?
What’s the point of this “_” technique?
In C, a struct must be used as:
…i.e., you must type
structnot only when you define thestruct, but also every time you use it. Thetypedefeliminates the typing ofstructwhen you use it (but not when you define it: there is no way to eliminate that). With atypedefthen, declaring an instance of thestructbecomes:Now, that doesn’t completely explain the
_StructA/StructAbusiness in the defining of thestruct/typedef, as you can do this:…here, we take an anonymous
structand immediately feed it totypedef. But using this method, you can’t use thestructinside itself, as it doesn’t (yet) have a name. For that, you need something like: