An external struct declaration, but the struct definition is just above

Viewed 51

I double-checked all the similar questions here, I really hope not to duplicate. I am intrigued by the the following extract from stdio.h:

typedef struct _iobuf {
    /* Members here omitted ... */
} FILE;
extern FILE _iob[20];

We define a new type named FILE by using the struct syntax. Just after that, we declare an extern variable _iob of type FILE. Therefore, this variable must come from another place. But, since the definition of FILE is in this file, how can it be possible? I see two possibilities only. The first is to have something like:

#include <stdio.h>
FILE _iob[20] = /* definition */

The second is to have another source file where the struct is copy-pasted and the variable declared, I guess a very bad practice that we can omit.

Since I am a self-learner, I would be very happy to receive a confirm of my understanding.Thanks!

1 Answers

Either:

  • somewhere in the library source code files, there is text as you describe, an inclusion of <stdio.h> followed by a definition of FILE _iob[20], or
  • somewhere in the library source code files, there is a definition of _iob written in a programming language other than standard C.

The latter may be assembly language, non-standard C with extensions, or something else. An implementation of C is not required to use only C source code to define itself.

In general, it is good practice for the source file that defines an object to also include its own header. A primary purpose of a header file is to tell other source files about things defined in the associated source file. But including the header file in the source file serves another purpose: The compiler will see both the declarations in the header and the definitions in the source file and will issue error messages if they are incompatible. So this provides a check that catches typos or other errors when building the library.

Related