Search code examples
cstructcompiler-errorsdoxygennaming

How to define a struct in a struct and reuse the same name twice?


I have a simple C code example using a struct in a struct.

  • I need for documentation (doxygen) a named struct, in my example HermannS.
  • In doxygen I can refer to age with \ref ottoS::HermannS::age.
  • In doxygen I can not use \ref ottoS.name.age etc
  • For logic the name HermannS have to be the same.

Problem: But now the code create an redefinition-error

struct ottoS {
  struct HermannS {
    int age;
  } name;
};

struct otherS {
  struct HermannS {
    int size;
  } name;
};

int main ()
{
  return 0;
}

I get the following error-message:

main.c:16:10: error: redefinition of ‘struct HermannS’
   struct HermannS {
          ^~~~~~~~
main.c:10:10: note: originally defined here
   struct HermannS {
          ^~~~~~~~

Question: how to define a struct in a struct and reuse the name HermannS ?

better Question: is there a gcc extension (prefix) to hide this error? → but this would be a very high price to pay for a simple doxygen documentation issue.


Solution

  • A struct declaration does not create a new namespace in C the way it does in C++, so you can't create type names that are "local" to a struct type. The tag name HermannS can only be used for one struct type definition.

    C has four name spaces:

    • all labels (disambiguated by : or goto);
    • all tag names (disambiguated by struct, union, or enum)
    • member names (disambiguated by . or ->)
    • all other names (typedef names, enumeration constants, variable names, function names, etc.)

    Unfortunately, what you're trying to do won't work in C - you'll have to use a different tag name for each inner struct definition.