【问题标题】:C - Unknown type nameC - 未知类型名称
【发布时间】:2018-10-27 03:45:09
【问题描述】:

我需要为大学建立一个“社交网络”,但我在编译时总是得到未知的类型名称“列表”。我从标题中删除了很多函数,但我仍然得到同样的错误,我不知道为什么。 我有 3 个标题:

我朋友的标题

#ifndef FRIEND_H
#define FRIEND_H

#include "ListHeadTail.h"

typedef struct Friend{
    int id;
    struct Friend *nextFriend;
}Friend;

void printFriends(List *l);
void removeFriend(List *l);
void addFriend(List *l);

#endif /* FRIEND_H */

我的列表标题:

#ifndef LISTHEADTAIL_H
#define LISTHEADTAIL_H

#include "Student.h"

typedef struct pStudent{
    struct pStudent *ant;
    Student *s;
    struct pStudent *prox;
}pStudent;

typedef struct list{
    pStudent *head;
    pStudent *tail;
}List;

void startList(List *l);
void printList(List *l);
void freeList(List *l);

#endif /* LISTHEADTAIL_H */

我学生的标题

#ifndef STUDENT_H
#define STUDENT_H

#define MAX 51

#include "Friend.h"
#include "ListHeadTail.h"

typedef struct Student{
    int id;
    char name[MAX];
    Friend *friends;
}Student;

Student* readStudent ();
void printStudent(Student* a);
void changeData(List *l);

#endif /* STUDENT_H */

我的主要:

#include <stdio.h>
#include <stdlib.h>

#include "ListHeadTail.h"
#include "Friend.h"
#include "Student.h"

int main(int argc, char** argv) {

    List l;

    startList(&l);

    freeList(&l);

    return (EXIT_SUCCESS);
}

感谢阅读。

【问题讨论】:

  • 您的main 首先包括ListHeadTail.h,其中将包括Student.h。然后Student.h 将包括Friend.h,全部按此顺序。 Student.h 将在实际定义之前尝试使用ListHeadTail.h 中定义的内容(ListHeadTail.h 的完整主体尚未被解析)。当你有循环依赖时,你需要使用forward declarations
  • 你是对的。我刚刚更改了我的代码,现在它可以工作了。谢谢。

标签: c struct


【解决方案1】:

这是我尝试编译这组文件时遇到的(第一个)错误:

$ cc main.c
In file included from main.c:4:
In file included from ./ListHeadTail.h:4:
In file included from ./Student.h:6:
./Friend.h:11:19: error: unknown type name 'List'
void printFriends(List *l);

查看文件名和行号。请注意,在 ListHeadTail.h 第 4 行,您已经定义了 LISTHEADTAIL_H,但尚未达到 List 的实际声明。然后进入 Student.h,然后从那里进入 Friend.h。这再次包括 ListHeadTail.h ——但由于 LISTHEADTAIL_H 已经定义,这个 include 什么都不做。因此,您在没有声明 List 的情况下继续浏览 Friend.h,因此在引用它的声明中会出现错误。

正如@lurker 在他们的评论中所指出的,这里的基本问题是循环依赖,一个简单的解决方法是前向声明。在这种情况下,您可以简单地修改 Friend.H,将 #include "ListHeadTail.h" 替换为 typedef struct list List;

但对我来说,这有点 hacky。如果您将包含的顺序转移到某处,则构建可能会再次中断。

我认为真正的问题是函数的声明(printFriends 等)不属于 Friend.h;它们属于 ListHeadTail.h。这些函数与Friend 类型无关。当然,他们的名字中有“朋友”,但声明中引用的唯一类型是List。所以它们属于 ListHeadTail.h。 Student.h 中的changeData 函数也是如此。

在面向对象的设计中(比如在 Java 中),这些函数都可能是 List 类的方法,并且会在该类的源文件中声明。

【讨论】:

  • 是的,你是对的,这些函数与 Friend 类型无关,我将尝试更改我的代码,以便我的 Friend 类型只获取与 Friend 相关的函数。谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
相关资源
最近更新 更多