从另一个文件调用节点 [英] Calling a node from another file

查看:49
本文介绍了从另一个文件调用节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在编程中保持简单并且能够改变是很重要的.所以对我来说,这意味着使用不同的文件和函数并将它们分开以更容易地隔离故障和提高可读性很重要.

I know that in programming it is important to keep things simple and be able to be changed. So to me that means it is important to use different files and functions and to keep them separate to easier isolate faults and improve readability.

我是 C 的新手,我不明白如何做到这一点.我有我的 nodeTest.h

I am new to C and I don't understand how to do this. I have my nodeTest.h

 #include <stdio.h>
 #include <stdlib.h>

 struct nodeTest
 {
     int data;
     struct nodeTest* next;

 };

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

Then I have another file trying to call that struct

 #include <stdio.h>
 #include <stdlib.h>
 #include "nodeTest.h"

 nodeTest* first = (nodeTest*)malloc(sizeof(nodeTest));

我收到一条错误消息,说 nodeTest 未声明(不在功能中).这是什么意思,为什么我不能使用 include 来包含 struct 或 typedef?

I am getting an error saying that nodeTest is undeclared(not in function). What does that mean and why can I not use include to include a struct or typedef?

推荐答案

你必须使用 struct NodeTest 而不是 NodeTest.

You have to use struct NodeTest instead of NodeTest.

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

Thats because C differentiates three namespaces:

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

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

So everywhere you want to use an struct, you have to specify the compiler that name refers to an struct. For example:

int main()
{
    struct NodeTest node;
}

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

One workaround to that problem is to specify an alias to that struct, to "add" the struct to the types namespace:

typedef NodeTest NodeTestType;

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

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

Or using the common idiom, declare directly the struct as an alias:

typedef struct { ... } NodeTest;

注意,这句话的作用是将一个名为NodeTest的别名赋予一个未命名的struct您已在同一指令中声明.
这种方法的一个问题是您不能在结构中使用该类型,因为它尚未声明.您可以通过命名结构来解决它:

Note that what this sentence does is to make an alias named NodeTest to an unnamed struct you have declared in the same instruction.
One problem of this approach is that you cannot use the type inside the struct, because its not declared yet. You could workaround it naming the struct:

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

这篇关于从另一个文件调用节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆