Forward declarations of unnamed struct

spraff picture spraff · Aug 31, 2011 · Viewed 16.8k times · Source

Bounty question: So, these two Foos aren't the same thing. Fine. The second form is given in a library. How do I forward-declare it given that I can't change it?


I always thought C and C++ allowed repeated declarations provided that there were no repeated definitions. Then I came across this problem when trying to write C++ code which extends a C library.

struct Foo;
typedef struct {} Foo;

This gives the following error:

'struct Foo' has a previous declaration as 'struct Foo'

I want to forward-declare, darn it! What's wrong here?

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · Aug 31, 2011

You're declaring two different entities with the same name. The first, struct Foo, is a struct named Foo. The second is an alias for an anonymous struct.

If you do instead:

struct Foo;
struct Foo {};

It works, because you're declaring a struct named Foo in both situations.

You cannot forward declare anonymous structs. You're left with two choices: include the whole definition, or change the header and name the struct.