3

I am using a legacy lib that defines a struct in Foo.h:

typedef struct { int i; int j; } Foo

However in my C++ program I am trying to write the following in a header file.

// forward-declare the struct
struct Foo;

class Bar {
  void myFunction(std::shared_ptr<Foo> foo);
};

And in my cpp file:

#include "Foo.h"

However this fails with an error:

typedef redefinition with different types ('struct Foo' vs 'Foo')

What is the correct syntax to do this?

hugo
  • 3,067
  • 2
  • 12
  • 22
Frank
  • 2,446
  • 7
  • 33
  • 67

1 Answers1

6

This typedef declaration

typedef struct { int i; int j; } Foo;

declares the alias Foo for an unnamed structure.

This declaration

struct Foo;

declares another structure with the name Foo.

These two structures are different. So the name Foo is ambiguous.

What you need is just to include the typedef declaration in your own header or to include the header Foo.h with the already declared typedef in your own header.

That is neither compilation unit shall contain two typedef declarations of the alias Foo because each unnamed structure introduces a different type though their data member declarations can be the same.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335