Pointer to undeclared structure-type considered ok?

Kevin P. Fleming kpfleming@starnetworks.us
Wed Feb 2 17:27:00 GMT 2005

Nick Patavalis wrote:

> In what sense is the "struct bar" type defined? Because if "struct
> bar" is not defined, then how can "struct bar *" be defined? Is it ok
> to to have pointer-type whose base type is not (or incompletely)
> defined?

This technique is used rather often to hide structure definitions from 
consumers of that structure. For example:

-- file foo.h --

struct foo;

extern struct foo *make_foo(void);
extern void destroy_foo(struct foo *);

-- file foo.c --

struct foo {
   int bar;
   int baz;
   char *bat;
   struct foo *next;

-- file foouser.c --

#include "foo.h"

static int do_the_work(void)
   struct foo *here_it_is;

   here_it_is = make_foo();

Simple, and works very well. All users of foo.h know that "struct foo" 
exists, and can store/retrieve pointers to one, and have functions to 
manipulate one. They just can't peek inside one.

More information about the Gcc-help mailing list