[英]C Unknown type name 'my_structure'
我有这个代码:
main.h
#ifndef MAINH
#define MAINH
...
#include "my_struct.h"
void some_func(my_structure *x);
...
#endif
和
my_struct.h
#ifndef UTILSH
#define UTILSH
...
#include "main.h"
...
typedef struct abcd {
int a;
} my_structure;
...
#endif
但是当我尝试编译时得到这个: error: unknown type name 'my_structure'
知道为什么吗?
由于您订购包含的方式,编译器会看到void some_func(my_structure *x);
在它看到typedef struct abcd { int a; } my_structure;
typedef struct abcd { int a; } my_structure;
.
让我们来看看这个。
假设首先处理my_struct.h
,我们得到以下事件序列:
UTILSH
已定义MAINH
已定义UTILSH
已经定义了,我们不再处理my_struct.h
,所以 typedef 没有被处理void some_func(my_structure *x);
被处理。typedef
。因此,在预处理之后,您的编译器会看到以下声明序列:
...
void some_func(my_structure *x);
...
typedef struct abcd {...} my_structure;
坏枣。 您要么需要在main.h
对my_structure
进行前向声明,要么需要打破这种循环依赖(这是更受欢迎的选项)。 main.h
中是否有my_structure.h
实际使用的内容? 如果是这样,您需要将其分解为main.h
和my_structure.h
包含的单独文件。
您创建了一个圆形标题包含。 循环包容永远不会取得任何成就。 它是无限的。 #ifndef
包含守卫将在某个不可预测的点打破无限包含圈(取决于哪个头文件首先包含在.c
文件中)。 这就是你的情况。 基本上,您的循环包含被“解析”为首先包含main.h
然后包含my_struct.h
。 这就是main.h
对my_struct
类型一无所知的原因。
同样,循环包含永远不会实现任何目标。 摆脱循环包含。 分层设计您的标题结构:将较低级别的标题包含在更高级别的标题中,但绝不会反过来。 在您的情况下my_struct.h
可能是一个较低级别的标头,这意味着您必须停止将main.h
包含到my_struct.h
。 重新设计您的标题,以便my_struct.h
不再需要main.h
。
该错误消息是来自main.h
而它包含在my_struct.h
,前my_structure
定义。 您应该重新考虑包含路径,因为main.h
和my_struct.h
相互包含。
您可能希望main.h
文件只包含my_struct.h
,而不要让my_struct.h
包含任何内容。 您实际上是在指示您的 C 编译器具有无限的 co-include 循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.