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

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

我有以下代码:

文件sched.h

   
   #ifndef __SCHED_H__
   #define __SCHED_H__

   #include <stats.h>

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

   #endif

文件stats.h

   #ifndef STATS_H
   #define STATS_H

   #include <sched.h>

   struct stats
   {
      int i;
   };
   #endif

我收到这个错误:

 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;
     |                ^~~~

显然 sched.h 文件在使用前没有看到 stats.h 文件的声明,但我不知道如何解决这个问题。

问题是,stats.h 文件中没有更多代码,sched.h 文件很长,但问题就出在那个声明上。我无法在虚拟程序中复制问题,但在我添加它之前一切正常。如果我删除 #include 一切正常。

这些是我用来编译的命令。我只是在创建目标文件。

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

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

你有 header 的递归包含。

在 header sched.h 你有

#include <stats.h>

另一方面,在 header stats.h 你有

#include <sched.h>

根据您提供的代码片段,不清楚 header sched.h 包含在 header stats.h 中的原因是什么。

在任何情况下,都应删除 header 之一中的 include 指令之一。

如果您在另一个结构定义中使用 struct stats 类型的数据成员,例如

struct task_struct {
    struct stats stat;
};

那么结构struct stats应该已经被定义了。即一个object这个类型的大小应该是已知的。否则为不完整类型。

重新设计您的 headers。