c++cstruct

Compiler circular reference


I defined two types in my code.

typedef struct Project Project;

typedef struct Worker{
  Project projects[10];
}Worker;

struct Project{
 Worker member[30];
}

The compilation process is throwing the following error:

array type has incomplete element type

I think is because of the circular reference, when the compiler is trying to allocate space to the array it does not know the type Project, and the same thing will happen if I change the definition order of the types. Am I right about the problem? And most important, how can I solve this problem?


Solution

  • You're correct. Your Worker struct contains the member of type Project by value. In order for the compiler to construct the Worker objects correctly it needs to know it size. This means it needs to have the complete definition of Project type - and in your code it's defined only a few lines later. You can go around this by using by having reference/pointer to a Project members in Worker struct and using forward declaration to announce it so the compiler will know it's a known type (the problem above is avoided since size of a pointer is independent of type it points to thus the compiler doesn't need the full type definition).

    Something like this:

    struct Project;  //forward declaration of Project type
    typedef struct Worker{
      Project *projects[10];
    } Worker;
    
    struct Project{
      Worker member[30];
    }