Search code examples
ccoding-styletypedefforward-declaration

using C struct that is declared later


I want use a typedef struct that isn't already defined, but it is later. Is there anything like a struct prototype?

file container.h

// i would place a sort of struct prototype here
typedef struct 
{
 TheType * the_type;
} Container;

file thetype.h

typedef struct {......} TheType;

file main.c

#include "container.h"
#include "thetype.h"
...

Solution

  • Replace this line:

    // i would place a sort of struct prototype here
    

    with these lines:

    struct TheType;
    typedef struct TheType TheType;
    

    Since you need the type TheType to be defined before type Container is defined, you have to use forward declaration of type TheType - and to do so you also need forward declaration of struct TheType.

    Then you will not define typedef TheType like this:

    typedef struct {......} TheType;
    

    but you will define struct TheType:

    struct TheType {......};