Search code examples
cheaderincludetypedef

Pure C: when using typdef void StructName in header file, the header file can't be included into the .c file


I have a header file that looks like this:

typedef void Square;

extern Square*  Square_Init       (int width, int height);
extern void     Square_Delete     (Cube* cube);
extern int      Square_GetWidth   (Cube* cube);
extern int      Square_GetHeight  (Cube* cube);

and a .c file, looking something like this:

/* #include "square.h" */ /* compiler gets mad for redefining Square */

typedef struct {
    unsigned int width;
    unsigned int height;
} Square;

Square* Square_Init (int width, int height) {. . .}

void Square_Delete (Cube* cube) {. . .}

int Square_GetWidth (Cube* cube)  {. . .}

int Square_GetHeight (Cube* cube) {. . .}

When I finally include my header file in let's say main.c, all the functions work well. It is just a bit odd for me, that I can't include the square.h file into the square.c file. Can it be done somehow?


Solution

  • What you seem to want to do is an opaque type. But void * is not a type compatible with struct pointers, so you cannot use them interchangeably, and most definitely cannot use void interchangeably with a structure type.


    The correct way is to use a tagged structure without definition in the header, for example:

    typedef struct square Square;
    

    and if you include the header in your .c file, you just need to add:

    struct square {
        unsigned int width;
        unsigned int height;
    };