我知道在编程中保持简单并且能够更改很重要。所以对我来说,这意味着使用不同的文件和函数并将它们分开以更容易地隔离故障并提高可读性是很重要的。
我是 C 的新手,我不知道该怎么做。我有我的 nodeTest.h
#include <stdio.h>
#include <stdlib.h>
struct nodeTest
{
int data;
struct nodeTest* next;
};
然后我有另一个文件试图调用那个结构
#include <stdio.h>
#include <stdlib.h>
#include "nodeTest.h"
nodeTest* first = (nodeTest*)malloc(sizeof(nodeTest));
我收到一条错误消息,指出 nodeTest 未声明(不在函数中)。这是什么意思,为什么我不能使用 include 来包含 struct 或 typedef?
最佳答案
您必须使用 struct NodeTest
而不是 NodeTest
。
那是因为 C 区分了三个命名空间:
- 结构的命名空间。
- 类型别名(类型名称)的命名空间。
- 枚举和 union 的命名空间。
因此,无论在何处要使用结构,都必须指定编译器名称指的是结构。例如:
int main()
{
struct NodeTest node;
}
该问题的一个解决方法是为该结构指定一个别名,以将该结构“添加”到类型命名空间:
typedef NodeTest NodeTestType;
int main()
{
NodeTestType node; //OK
}
或者使用常见的习惯用法,直接将结构声明为别名:
typedef struct { ... } NodeTest;
请注意,这句话所做的是为一个未命名的结构创建一个名为 NodeTest
的别名
您已在同一指令中声明。
这种方法的一个问题是您不能使用结构内部的类型,因为它尚未声明。您可以解决它命名结构:
typedef struct nodeTest //<-- Note that the struct is not anonimous
{
int data;
struct nodeTest* next;
} nodeTest;
关于从另一个文件调用节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19201630/