Search code examples
cstructtypedefdefinitionincomplete-type

C - Variable has incomplete type "struct ..."


I have a container.h file and a container.c file.

In the container.h file, I've written the following:

typedef struct Container Container;

And the following in the container.c file:

#include "container.h"

typedef struct Container
{
  size_t item_count;
} Container;

However, I keep getting the variable has incomplete type "struct Container" error. Is this something that has to do with using extern with struct or something?

Edit: I have compiled the following as a library and #include-d it in another main.c file where I wrote the following:

#include "library.h"

int main()
{
  Container ctnr = { 0 };

  return 0;
}

Solution

  • It means that the only translation unit that knows the structure definition is the translation unit with the file container.c.

    If any other translation unit needs to know the structure definition then the compiler will issue an error because the structure definition is not available. You need to place the structure definition in the header.

    That is the translation unit with the function main

    #include "library.h"
    
    int main()
    {
      Container ctnr = { 0 };
    
      return 0;
    }
    

    needs to know the structure definition to allocate memory for the object ctnr. But the structure definition is not available. So the compiler at least does not know how much memory to allocate. Also there is no need to use two typedef(s) with the same name. One of typedef(s) is redundant.