【问题标题】:What is causing an Identifier Error in C from Header File?是什么导致头文件中的 C 中出现标识符错误?
【发布时间】:2021-07-30 05:48:27
【问题描述】:

我是 C 新手,似乎对头文件的工作方式有误解。 为简单起见,我有三个文件:tree.h、lib.c 和 main.c

在tree.h中,我有

struct Node
{
    void* item;
    Node** nodes;
};

struct Tree
{
    Node* tree_root;
    int depth, item_size;
};

void initializeTree(Tree*, int);

据我了解,此 initializeTree 方法是一个函数“签名”,并且每当我在 lib.c 或包含头文件的任何其他 .c 文件中调用该函数时,编译器都会对该函数有所了解树.h。 但是,在 lib.c 中出现错误“标识符树未定义”。

#include <tree.h>

void initializeTree(Tree* tree, int item_size)

是什么导致了这个错误?编译器是否无法从包含的头文件中“看到” Tree 结构?

【问题讨论】:

  • Tree* tree -> struct Tree* treestruct 关键字是类型名称的一部分。或者,您可以使用 typedef 创建一个没有 struct 的别名。
  • 和... Node** nodes; --> struct Node** nodes;

标签: c header-files


【解决方案1】:

没有Tree,只有struct Tree(a)。虽然 C++ 允许使用缩写形式,但 C 不允许。

在 C++ 中,structclass 的细微变化,它们都是可访问的类型没有 struct/class 前缀。但是,C 中的规则是不同的,因为尽管这两种语言有相似之处和历史,但它们现在是非常不同的野兽。

因此,在 C 中,您要么必须使用 full 类型名称:

struct Tree { blah blah };
void initializeTree(struct Tree *, int);

typedef 这样:

typedef struct sTree { blah blah } Tree; // struct sTree =~ Tree
void initializeTree(Tree *, int);

(a)顺便说一句,您与Node相同的问题。

【讨论】:

  • C++ 是一种不同的语言。关键字struct 声明了一个类,它是一种数据类型,但具有除class 之外的其他默认可访问性。这就是为什么你不需要在 C++ 中typedef
猜你喜欢
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
  • 2019-08-31
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
相关资源
最近更新 更多