6

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.

Community
  • 1
  • 1
Ghasan غسان
  • 5,577
  • 4
  • 33
  • 44
  • can you show the exact error message being show when you try to compile/link your program – unkulunkulu Jun 22 '12 at 15:09
  • error: redefinition of "struct entry". It is because that I included the file to another that uses the same name. It appears it is a logical error of isolating design from implementation, in which translation units need only to communicate through header files, not directly. – Ghasan غسان Jun 22 '12 at 15:25

2 Answers2

9

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.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • 2
    ...or are including a file with a struct, union, or enum of that name. – T.E.D. Jun 22 '12 at 15:11
  • This was my problem: "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." Thanks a lot. – Ghasan غسان Jun 22 '12 at 15:21
  • @ecatmur - So this is wrong: http://www.dmst.aueb.gr/dds/cscout/doc/name.html ? It wouldn't shock me, but does annoy me. I didn't have a C99 standard handy to double-check it with. – T.E.D. Jun 22 '12 at 15:26
  • 2
    Sorry, I'm wrong; 6.2.3 footnote 24: "There is only one name space for tags even though three are possible." – ecatmur Jun 22 '12 at 15:50
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.

David Grayson
  • 84,103
  • 24
  • 152
  • 189