【发布时间】:2021-04-07 08:55:56
【问题描述】:
假设我有这样一个项目结构:
main.c
#include "hashtable.h"
#include "list.h"
int main()
{
hash_table ht = calloc(1, sizeof(htable));
cmp_function f;
TLDI list;
return 0;
}
hashtable.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _HASH_TABLE_
#define _HASH_TABLE_
#include "list.h"
typedef int (*hash_function)(void*, int);
typedef struct _hasht_{
int maxElemNumber;
hash_function hf;
TLDI* key_array;
} htable, *hash_table;
void test2(cmp_function cmp);
#endif
list.h
#include "hashtable.h"
#ifndef _LINKED_LIST_
#define _LINKED_LIST_
typedef int (*cmp_function)(void*, void*);
typedef struct _node_ {
void *info;
struct _node_ *pre, *urm;
} TNode, *TLDI;
int test(hash_table ht);
#endif
还有另外两个 C 文件:
hash_func.c
#include "hashtable.h"
void test2(cmp_function cmp)
{
printf("test\n");
}
list_func.c
#include "list.h"
int test(hash_table ht)
{
return 1;
}
我想在hashtable.h 中使用来自list.h 的typedef,它是typedef struct...},*TLDI;。同样,list.h 使用来自hashtable.h 的typedef struct ...},*hash_table;。我可以做这样的事情还是我错了?因为编译整个项目时出现此错误:
In file included from hashtable.h:7,
from main.c:1:
list.h:14:10: error: unknown type name ‘hash_table’
14 | int test(hash_table ht);
In file included from hashtable.h:7,
from hash_func.c:1:
list.h:14:10: error: unknown type name ‘hash_table’
14 | int test(hash_table ht);
我不擅长typedef 和标题,但如果我能得到这个问题的答案,或者至少能找到一个可以找到更多关于它们的来源,我将非常感激。
【问题讨论】:
-
我只是希望人们停止使用 typedef。停止在头文件中隐藏逻辑。但是,如果您真的需要,请仅使用类型定义创建第三个头文件,并将其包含在其他头文件中。然而,我真的很担心你在 list.h 中包含 hash_table.h,这根本没有意义。
-
你不能有相互递归的头文件。将您的
test函数提取到不同的标题中,这样就没有循环依赖。或者,您可以解决结构的前向声明。