从另一个文件调用节点

我知道在编程中,保持简单并能够改变是很重要的。 所以对我而言,这意味着使用不同的文件和function并将它们分开以便更容易隔离故障并提高可读性非常重要。

我是C的新手,我不明白该怎么做。 我有我的nodeTest.h

#include  #include  struct nodeTest { int data; struct nodeTest* next; }; 

然后我有另一个文件试图调用该结构

  #include  #include  #include "nodeTest.h" nodeTest* first = (nodeTest*)malloc(sizeof(nodeTest)); 

我收到一个错误,说nodeTest未声明(不在函数中)。 这是什么意思,为什么我不能使用include来包含struct或typedef?

您必须使用struct NodeTest而不是NodeTest

那是因为C区分了三个命名空间:

  • 结构的命名空间。
  • 别名类型的名称空间(类型名称)。
  • 枚举和联合的命名空间。

因此,无论您想在何处使用结构,都必须指定名称引用结构的编译器。 例如:

 int main() { struct NodeTest node; } 

该问题的一个解决方法是指定该结构的别名,以将结构“添加”到类型命名空间:

 typedef NodeTest NodeTestType; int main() { NodeTestType node; //OK } 

或者使用常用的习惯用法,直接将结构声明为别名:

 typedef struct { ... } NodeTest; 

请注意,这句话的作用是将一个名为NodeTest的别名NodeTest为您在同一指令中声明的未命名结构。
这种方法的一个问题是你不能在结构中使用类型,因为它尚未声明。 您可以解决命名结构的问题:

  typedef struct nodeTest //<-- Note that the struct is not anonimous { int data; struct nodeTest* next; } nodeTest; 

在全局范围内,您可以只声明/定义函数,结构或全局变量。 你不能像那样调用一个函数(字面意思是“无处不在”)。 从内部创建一个main并调用malloc

 int main(void) { nodeTest* first = (nodeTest*) malloc(sizeof(nodeTest)); free(first); return 0; } 

 struct nodeTest { int data; struct nodeTest* next; }; 

定义struct nodeTest

 nodeTest* first; 

编译器不知道。 要解决这个问题,你可以使用:

 struct nodeTest* first; 

甚至更好:在定义struct使用typedef ,一切都会好的:

 typedef struct nodeTest { int data; struct nodeTest* next; } nodeTest ; 

你需要定义nodetest类型

 typedef struct nodeTest_t { int data; struct nodeTest_t* next; }nodeTest; 

要不然
在main()中,在nodeTest之前使用struct关键字。

只需将代码放在这样的函数中:

 #include  #include  #include "nodeTest.h" int main(void) { struct nodeTest* first = malloc(sizeof(struct nodeTest)); return 0; }