Search code examples
ccoding-stylestructtypedefopaque-pointers

Opaque C structs: various ways to declare them


I've seen both of the following two styles of declaring opaque types in C APIs. What are the various ways to declare opaque structs/pointers in C? Is there any clear advantage to using one style over the other?

Option 1

// foo.h
typedef struct foo * fooRef;
void doStuff(fooRef f);

// foo.c
struct foo {
    int x;
    int y;
};

Option 2

// foo.h
typedef struct _foo foo;
void doStuff(foo *f);

// foo.c
struct _foo {
    int x;
    int y;
};

Solution

  • My vote is for the third option that mouviciel posted then deleted:

    I have seen a third way:

    // foo.h
    struct foo;
    void doStuff(struct foo *f);
    
    // foo.c
    struct foo {
        int x;
        int y;
    };
    

    If you really can't stand typing the struct keyword, typedef struct foo foo; (note: get rid of the useless and problematic underscore) is acceptable. But whatever you do, never use typedef to define names for pointer types. It hides the extremely important piece of information that variables of this type reference an object which could be modified whenever you pass them to functions, and it makes dealing with differently-qualified (for instance, const-qualified) versions of the pointer a major pain.