Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Limit struct Scope

Tags:

c

scope

struct

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.

like image 222
Ghasan غسان Avatar asked Jun 22 '12 15:06

Ghasan غسان


2 Answers

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.

like image 171
ecatmur Avatar answered Oct 14 '22 05:10

ecatmur


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.

like image 29
David Grayson Avatar answered Oct 14 '22 04:10

David Grayson