Alex Rivera | Logout

Forward declare FILE *

Asked 2010-10-07T13:55:25.477
18

How do I forward declare FILE * in C? I normally do this using struct MyType;, but naturally this doesn't appear to be possible.

If behaviour differs between C standards or compilers and with C++, this is also of interest.

Update0

Why I want to do this aside: What I'm asking is how to forward declare a non-struct/"typedef'd struct" type so that I can declare pointers to it. Obviously using void * and casting it in the source file is a bit hackish.

Edit
Report

2 Answers

25

You can't. The standard just states that FILE is "an object type capable of recording all the information needed to control a stream"; it's up to the implementation whether this is a typedef of a struct (whose name you don't know anyway), or something else.

The only portable way to declare FILE is with #include <stdio.h> (or <cstdio> in C++).

answered 2010-10-07T14:03:35.583
11

If you #include <stdio.h> you should get the FILE typedef with it. That's the only really safe and portable way -- you can't have a typedef without a type to alias, and there's no guarantee about what type FILE aliases, so every compiler or libc or whatever can have a different one. But you'd need the type to be correct in case anyone actually wants to #include <stdio.h>, lest the inconsistent definitions cause an error.

Edit:

Now that i think about it, there might be one other way i can think of. It's not a typedef, it's evil macro stuff that works by hijacking the definition of "FILE". I wouldn't recommend it for that reason alone. But it might work for what you need.

#ifdef USES_REAL_FILE_TYPE
#include <stdio.h>
#else
#define FILE void
#endif

/* declare your struct here */

#ifndef USES_REAL_FILE_TYPE
#undef FILE
#endif

Then #define USES_REAL_FILE_TYPE before you include the file in any code where you need a real FILE *, and the rest of the code will just see the pointer as a void *.

I make no guarantees that this won't mess stuff up. In particular, it will break in any case where you want to know anything real about such a fake type, and all code that touches the pointer may need that #define. But if you're dead set against "unnecessary" #includes, it's the only way you're gonna get a FILE * without interfering with stdio. You're not going to be able to forward declare a typedef.

Edit2:

OK, i checked just to make sure. Not sure how standard it is,or what you can do with it, but...

typedef FILE;

works in Visual C and GCC both, but only when compiling C code. It would appear that the C++ standard explicitly says somewhere that you can't have a typedef without a type. The C one, though, doesn't.

However, it

answered 2010-10-07T14:01:58.580

Your Answer