extern 用于 C 中新定义的结构
我在 main 中使用了节点结构,但是节点的定义及其操作操作位于名为 NODE/ 的目录中的文件中,
我创建了 NODE/node.h,其中包含:
typedef struct node node;
struct node
{
int my_reg;
node *left;
node *right;
} ;
我创建了 NODE/node.c 并包含在其中node.h 其中有node_insert node_remove;
但是,我在 school_address.c 中使用节点结构,其中还包含 NODE/node.h 和 NODE/node.c
我尝试将
extern struct node
放入school_address.c
但代码没有编译并抱怨 node.h 中的重新定义
有什么想法吗?
I have main in which I used the node struct however defintion of node and it's manipulation operations are localed in a file in the directory called NODE/
I created NODE/node.h which has:
typedef struct node node;
struct node
{
int my_reg;
node *left;
node *right;
} ;
I created NODE/node.c and include in it node.h which has node_insert node_remove;
However I am using the node struction in school_address.c in which I also include NODE/node.h and NODE/node.c
I tried putting
extern struct node
in school_address.c
Yet the code doesn't compile and complains of redefinition in node.h
Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
extern
用于变量,而不是类型定义。您应该只在需要了解struct node
的所有模块中包含标头;它替换了整个标头的内容,内联。您不应该做的是将一个 C 文件包含在另一个 C 文件中。相反,您应该在标头中声明常用函数的原型。
例如
,如果您将
node_insert
的原型放入标头中,那么在 C 预处理器处理完它之后,就会变成
struct node
和node_insert
在main
中可见。extern
is for variables, not type definitions. You should just include the header in all modules that need to know aboutstruct node
; that is substituted for the entire header's content, inline.What you should not do is include a C file in another C file. Instead, you should declare the prototypes of the common functions in a header.
E.g.,
becomes, if you put the prototype for
node_insert
in the header,after the C preprocessor is done with it, so
struct node
andnode_insert
are visible inmain
.您正在寻找包含防护。
具体来说,
在node.h的开头使用,并
在其末尾对应。
另外,请勿包含
.c
文件。You are looking for an Include Guard.
Specifically, use
at the beginning of node.h, and the corresponding
at the end of it.
Also, do not include
.c
files.当您的头文件被多个 C 文件包含时,您必须将它们包含在预处理器指令中以避免重复定义,例如:
无论如何,在所有头文件中执行此操作是一个很好的做法。
When your header files are included by multiple C files you have to include them in preprocessor directives to avoid double definitions, such as:
It's good practice to do this anyway in all your header files.