Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

c++ - Forward declarations of unnamed struct

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

typedef-ing anonymous struct is a practice that pre-dates C++03 and is mainly oriented to retain compatibility with pre-C99 compilers.

Given that this is 2011, and that both C++ and C are changed, I wonder why there is no more up-to-date version of such a library!

If it is not in development anymore, you cannot "leave", but just "survive" and change it is the way to do that. If still in deployment, submit the issue to the development team.

If you need a workaround, consider that struct can inherit. So, write a forward declaration like

struct MyFoo;

and define it as

#include "old_library.h"
struct MyFoo: public Foo {};

And in all your code, forget about Foo and always use MyFoo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...