I was digging into a 3rd party code base and found that it is apparently valid to declare a type as a pointer to an undefined struct. As a minimum working example, consider a C file test.c
containing nothing but:
typedef struct foo *bar;
What surprises me is that this file compiles without any problems using the command
gcc test.c -shared
Why does the compiler not complain about the struct foo not being declared anywhere?
My environment is Ubuntu 16.04 with gcc (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609.
Because pointer to structs have same size (for any structs). The size of a structure pointer doesn't depend on it's definition. Because no matter what, the pointer to it would be behaved the same way as any other structures pointer.
The declaration above creates a forward declaration of
struct foo
. Although you can't access its members, you can operate on a pointer to it.This is commonly referred to as an opaque type, and is used to hide implementation details of a library from users of the library.
For example a library implementation may contain the following:
lib.c:
The header file for this library might look like this:
lib.h:
The user of this library would use the
init
function to create an instance of the struct and theset1
andget1
functions to read / update the member. The user can't however create an instance ofstruct foo
or access the members without going through one of the interface functions.