Search code examples
cstructheaderdeclaration

Problem with declaration of structs in header files: "error: field 'stat' has incimplete type"


I have the following code:

File sched.h

   
   #ifndef __SCHED_H__
   #define __SCHED_H__

   #include <stats.h>

   struct stats;
   struct task_struct {
       struct stats stat;
   };

   #endif

File stats.h

   #ifndef STATS_H
   #define STATS_H

   #include <sched.h>

   struct stats
   {
      int i;
   };
   #endif

I am getting this error:

 In file included from include/stats.h:6,
                 from stats.c:1:
include/sched.h:30:16: error: field ‘stat’ has incomplete type
  30 |   struct stats stat;
     |                ^~~~

Clearly the sched.h file is not seeing the declaration of the stats.h file before using it, but i dont have any idea on how this can be fixed.

The thing is, there is not much more code in the stats.h file, and the sched.h file is quite long, but the problem is just with that declaration. I have not been able to replicate the problem in a dummy program tho, but everything was working fine till I added this. If I remove the #include <sched.h> everything works fine.

These are the commands I am using to compile. I am just creating the object files.

tats.o:stats.c $(INCLUDEDIR)/stats.h

sched.o:sched.c $(INCLUDEDIR)/sched.h  

Solution

  • You have recursive inclusions of headers.

    In the header sched.h you have

    #include <stats.h>
    

    On the other hand, in the header stats.h you have

    #include <sched.h>
    

    From presented by you code snippet it is unclear what is the reason of inclusion the header sched.h within the header stats.h includes .

    In any case one of the include directives in one of the headers should be removed.

    If you are using a data member of the type struct stats in another structure definition like

    struct task_struct {
        struct stats stat;
    };
    

    then the structure struct stats shall be already defined. That is the size of an object of this type shall be known. Otherwise it is an incomplete type.

    Redesign your headers.