cstructdeclarationtypedefcircular-dependency

how to get rid of circular dependencies in C


I'm new to C and I'm stuck on this problem. In C# doing something like this is perfectly ok but in C the compiler works different and it needs to know the type definitions before hand.

struct FN;

typedef struct {
    void (*create) (FN *fn);
} Window;

typedef struct {
    Window window;
} FN;

Is there some kind of C trick with pointers etc that I can use to get it working? I'm trying to create like a "manager" class where I can call functions on my modules and then just pass the manager around where needed.


Solution

  • In the shown code you first declare a structure (not a type) named FN. Then later you redefine FN as a type-name. Besides this conflicting declarations you can't use FN as a type because it's initially not a type-name.

    If you can live with FN being a structure tag name you could just use

    typedef struct {
        void (*create) (struct FN *fn);
    } Window;
    
    struct FN
    {
        Window window;
    };
    

    If you want to make FN a type-name then declare the structure but define the type-name:

    typedef struct FN FN;  // Yes, structures and type-names can have the same name
    
    typedef struct {
        void (*create) (FN *fn);
    } Window;
    
    struct FN
    {
        Window window;
    };