6
struct mystruct
{
    int   i;
    double f;
} ;

typedef mystruct myotherstruct;

//the other .cpp file
struct mystruct;  //OK,this is a correct forward declaration.
struct myotherstruct; // error C2371(in vc2k8): 'myotherstruct' : redefinition; different basic types

Hi all. Why can't I forward declare myotherstruct?

Leonhart Squall
  • 810
  • 1
  • 7
  • 15

2 Answers2

1

You can't forward declare typedefs without forward declaration of the struct that is typedefed. You should first forward declare the struct and then typedef

struct mystruct;
typedef mystruct myotherstruct;
Andrew
  • 24,218
  • 13
  • 61
  • 90
1

The myotherstruct identifier is not a struct tag, it is a type name in its own rights. You use it without the struct keyword. Once defined, the name cannot be reused for a struct tag. In your example, you are not forward-declaring myotherstruct type, you are forward-declaring a struct with the tag myotherstruct, which gives you an error because the name myotherstruct has already been taken for the typedef.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Is a struct tag equivalent to a name of type? mystruct m; – Leonhart Squall Jul 19 '12 at 11:10
  • @LeonhartSquall Curiously, the answer to this question depends on whether this is C++ or C: in C++, structure's tag can be used as a name without `typedef`, while in C you must `typedef` it first. – Sergey Kalinichenko Jul 19 '12 at 11:12
  • Is a struct tag equivalent to a name of type? when I use mystruct to define a object: mystruct m; I always think mystruct is a type name. And I never know it is a struct tag.How can I undersand the struct tag. – Leonhart Squall Jul 19 '12 at 11:16
  • @LeonhartSquall In your example in C++, `mystruct` is both a tag and a type name. You can declare a variable of type `mystruct` either as `mystruct m;` or as `struct mystruct m;`, both declarations are OK. In C only the second one would be OK. You would need to add a `typedef struct mystruct mystruct;` on order to use the first form of declaration (i.e. without the `struct` keyword). – Sergey Kalinichenko Jul 19 '12 at 11:21
  • Can I think like this: forward-declaring only corresponds to a struct tag not to a type name. – Leonhart Squall Jul 19 '12 at 11:45
  • @LeonhartSquall In C++, it would be more precise to say that forward declaring corresponds only to "primary" type names (which include struct tags, because they implicitly define type names in C++) but not to type *aliases*, which are "secondary" type names created from other type names. – Sergey Kalinichenko Jul 19 '12 at 11:53