C - Limit struct Scope

2019-04-08 20:38发布

问题:

I am having this structure in a .c file:

struct entry {
    int position;
    int length;
    struct entry *node;
};

Now, how can I limit the scope of this structure layout to the host file, so that when using the same name for a new structure layout in another file, I don't get 'redefinition' error?

I tried using static before struct, but it seems of no use (I also doesn't make sense). BTW, this question doesn't seem valid to me, as that I get 'redefinition' error when duplicating stuct entry across linked files (using MinGW).

--- Edit ---
For those who want to know more: here, and here.

回答1:

You won't get a redefinition error. Types are local to translation units, and don't have any visibility. Only functions and data objects have visibility.

If you're getting a redefinition error, you must be using that name in a header or other included file so it ends up in the same translation unit.



回答2:

It sounds like you want to have struct entry mean different things in different files. That's fine: just put the codes for defining each version of the struct in different .c files, and make sure to never include a c file from another c file or include a c file from a header file.

Only one definition of the struct should exist in each translation unit.



标签: c struct scope