简体   繁体   中英

How to name structs and types correctly in C?

I have tried to find out, how to name a struct and type correctly. I always found what not to do ("__name", "_Name"), so I always did it like this:

typedef struct something_t {
    ...
} something_t;
// or
typedef struct something_that_should_not_be_copied_t {
    ...
} something_that_should_not_be_copied_t[1];

But I think this is not fully correct, because _t is reserved for type names, so "struct something_t" is not allowed. I also heard, that "struct something_s" is correct, but I have never seen it in any code base. So please, tell me, what is the correct way to do this in a normal program and in a library.

When using typedef struct { } name; , you don't even need to state a struct tag. This is only required if you are doing something special like a self-referencing struct or an implementation of "opaque types". So the most common solution would simply be to omit the struct tag.

struct tags and typedef names exist in different name spaces, so you can name them the same if you fancy, as far as the C language is concerned.

There is as far as I know no convention for naming struct tags. However, some coding standards like the Linux kernel encourages struct tag over typedef, for completely subjective reasons.

_t at the end of a type is a common naming convention for types however. It is fine to use, although prohibited by the POSIX standard.

Depending on what kind of application you are writing, you could either follow things like the Linux kernel coding style or POSIX, or you can completely ignore them.

My convention is to add the suffix Desc (descriptor) for the record type (struct). This convention is used in the Oberon programming language. If the type is a part of a module inteface I also add the module name with an underscore as a prefix. For instance, if I have a module Stacks I would declare the stack type in the header file Stacks.h as

typedef struct Stacks_StackDesc *Stacks_Stack;

and define it in the implementation file Stacks.c as something like

struct Stacks_StackDesc {
    int items[100];
    int count;
};

I now have an abstract data type names Stacks_Stack .

Adding a module prefix for the type may seem superfluous but it makes the code more consistent if each exported identifier has it. If you search for the string "Stacks_" in a client module you can easily see all identifiers used from module Stacks , like Stacks_Push , Stacks_Pop etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM