繁体   English   中英

C 未知类型名称“my_structure”

[英]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 ,我们得到以下事件序列:

  1. UTILSH已定义
  2. MAINH已定义
  3. 因为UTILSH已经定义了,我们不再处理my_struct.h ,所以 typedef 没有被处理
  4. void some_func(my_structure *x); 被处理。
  5. 现在处理typedef

因此,在预处理之后,您的编译器会看到以下声明序列:

...
void some_func(my_structure *x);
...
typedef struct abcd {...} my_structure;

坏枣。 您要么需要在main.hmy_structure进行前向声明,要么需要打破这种循环依赖(这是更受欢迎的选项)。 main.h中是否有my_structure.h实际使用的内容? 如果是这样,您需要将其分解为main.hmy_structure.h包含的单独文件。

您创建了一个圆形标题包含。 循环包容永远不会取得任何成就。 它是无限的。 #ifndef包含守卫将在某个不可预测的点打破无限包含圈(取决于哪个头文件首先包含在.c文件中)。 这就是你的情况。 基本上,您的循环包含被“解析”为首先包含main.h然后包含my_struct.h 这就是main.hmy_struct类型一无所知的原因。

同样,循环包含永远不会实现任何目标。 摆脱循环包含。 分层设计您的标题结构:将较低级别的标题包含在更高级别的标题中,但绝不会反过来。 在您的情况下my_struct.h可能是一个较低级别的标头,这意味着您必须停止将main.h包含到my_struct.h 重新设计您的标题,以便my_struct.h不再需要main.h

该错误消息是来自main.h而它包含在my_struct.h ,前my_structure定义。 您应该重新考虑包含路径,因为main.hmy_struct.h相互包含。

您可能希望main.h文件只包含my_struct.h ,而不要让my_struct.h包含任何内容。 您实际上是在指示您的 C 编译器具有无限的 co-include 循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM