【问题标题】:Unkown type error when using typedef struct使用 typedef struct 时出现未知类型错误
【发布时间】:2018-04-16 00:24:12
【问题描述】:

我知道有很多问题在问这个问题,但我已经查看了很多问题,但我仍然无法弄清楚问题所在。这一定是一些简单的错误,但我已经将这个结构声明和使用与我在同一个项目中使用的另一个(没有错误)进行了比较,它们在我看来是一样的。

我在 trie.h 中声明了这个结构:

#ifndef TRIE_H
#define TRIE_H

#include "fw.h"
#include "linked.h"

#define ALPHABET_SIZE 26

typedef struct T_node
{
   /* number of times this word has been found 
      (stored at end of word) */
   int freq;
   /* is_end is true if this T_node is the end of a word 
      in which case it */
   int is_end;
   /* each node points to an array of T_nodes
      depending on what letter comes next */
   struct T_node *next[ALPHABET_SIZE];
} T_node;

int add_word(T_node *root, char *word);
T_node *create_node(void);
void max_freqs(T_node *root, int num, List *freq_words, char *word,
               int word_len, int i);
void free_trie(T_node *root);

#endif

我在 fw.h 中使用它:

#ifndef FW_H
#define FW_H

#include <stdio.h>

#include "trie.h"

#define FALSE 0
#define TRUE 1

int read_file(FILE *in, T_node *root);
char *read_long_word(FILE *in);

#endif

我得到这个错误:

In file included from trie.h:4:0,
             from trie.c:5:
fw.h:11:25: error: unknown type name T_node
 int read_file(FILE *in, T_node *root);
                         ^

编辑:我不认为这是链接问题的重复。如果您查看最佳答案,似乎提供的结构与我的 T_node 当前的格式相同。此外,我没有收到与该问题相同的错误。

【问题讨论】:

  • 你能发帖َa minimal reproducible example吗?
  • @gzh 不是那个重复的,注意这里有struct T_node *next[ALPHABET_SIZE];,没错。
  • @IharobAlAsimi 好的,我放了完整的头文件。我认为它们不相关,但它们可能有用。
  • @dumbitdownjr 您的问题已在下面得到解答。看一看。您需要确保一个文件只包含一次。一个简单的方法是使用所谓的include guards,只是#ifndef MY_FANCY_HEADER_FILE,然后在下一行#define MY_FANCY_HEADER_FILE和文件末尾#endif。这样,即使您多次包含该文件,编译器也只会包含它的内容,直到您定义 MY_FANCY_HEADER_FILE 宏,因此它只会被包含一次。
  • 问题中的fw.h 根本不使用T_node 并且错误消息中没有该行。看起来你不小心包含了linked.h?无论哪种方式,如果您在trie.h 中包含fw.h,那么使用在fw.h 中包含之后 定义的东西是没有意义的,因为它不会看到它。

标签: c struct typedef


【解决方案1】:

错误信息

In file included from trie.h:4:0,
             from trie.c:5:
fw.h:11:25: error: unknown type name T_node
 int read_file(FILE *in, T_node *root);
                         ^

trie.c 包括trie.h,其中包括fw.h

但我们也看到fw.h 包含trie.h。这样我们就有了一个完整的圆圈。


如果可能,使用前向声明的结构 int read_file(FILE *in, struct T_node *root); 并从 fw.h 中删除 trie.h 包含。

【讨论】:

  • 所以这是不允许的?我在 trie.c 中需要 fw.h,在 fw.h 中我也需要 trie.h。这是否意味着我应该将它们合并到一个头文件中?
  • 必须组织代码,以免出现循环包含。您不需要结构的完整声明,只需将指向它的指针作为参数传递。为此,使用前向声明 struct T_node; 就足够了。
猜你喜欢
  • 2017-03-23
  • 2018-01-27
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
相关资源
最近更新 更多