[英]C - Unknown type name
我需要為大學建立一個“社交網絡”,但是在編譯時我總是得到未知的類型名稱“ List”。 我從標頭中刪除了很多功能,但是仍然出現相同的錯誤,我也不知道為什么。 我有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);
}
謝謝閱讀。
這是我嘗試編譯這組文件時遇到的(第一個)錯誤:
$ 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不會執行任何操作。 因此,您將繼續通過Friend.h而不使用List
聲明,因此在引用它的聲明中會出現錯誤。
正如@lurker在評論中指出的那樣,這里的基本問題是循環依賴,而簡單的解決方法是前向聲明。 在這種情況下,您可以簡單地修改Friend.H,用typedef struct list List;
替換#include "ListHeadTail.h"
typedef struct list List;
。
但是對我來說,這有點hacky。 如果將include的順序更改到某個位置,則構建可能會再次中斷。
我認為真正的問題是函數的聲明( printFriends
等)不屬於Friend.h; 它們屬於ListHeadTail.h。 這些功能與Friend
類型無關。 當然,它們的名稱中帶有“ Friend”,但是聲明中引用的唯一類型是List
。 因此,它們屬於ListHeadTail.h。 Student.h中的changeData
函數也是如此。
在面向對象的設計中(例如,在Java中),這些函數都可能是List類的方法,並將在該類的源文件中聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.