【问题标题】:C - Variable has incomplete type "struct ..."C - 变量的类型不完整“struct ...”
【发布时间】:2021-03-19 04:16:30
【问题描述】:

我有一个container.h 文件和一个container.c 文件。

在container.h 文件中,我写了以下内容:

typedef struct Container Container;

container.c 文件中的以下内容:

#include "container.h"

typedef struct Container
{
  size_t item_count;
} Container;

但是,我不断收到variable has incomplete type "struct Container" 错误。这与将extern 与 struct 一起使用有关吗?

编辑:我已将以下内容编译为库并将 #include-d 编译到另一个 main.c 文件中,我在其中编写了以下内容:

#include "library.h"

int main()
{
  Container ctnr = { 0 };

  return 0;
}

【问题讨论】:

  • 这是产生问题的准确和完整的代码吗?它没有任何变量声明,所以我认为不是。请提供complete minimal verifiable example 以及准确和完整的错误消息(包括行号)。
  • @kaylum 我错过了一部分可能我会修改我的答案。

标签: c struct typedef definition incomplete-type


【解决方案1】:

表示唯一知道结构定义的翻译单元是文件container.c的翻译单元。

如果任何其他翻译单元需要知道结构定义,那么编译器将发出错误,因为结构定义不可用。您需要将结构定义放在标题中。

也就是带有main函数的翻译单元

#include "library.h"

int main()
{
  Container ctnr = { 0 };

  return 0;
}

需要知道为对象ctnr分配内存的结构定义。但结构定义不可用。所以编译器至少不知道要分配多少内存。 也没有必要使用两个具有相同名称的 typedef(s)。 typedef(s) 之一是多余的。

【讨论】:

  • 感谢您的回答。我在这里真的是个菜鸟,所以我不太明白你的意思,或者说为什么会这样。我会尝试对您的答案进行一些研究以理解它,所以谢谢,但我还不能接受。
  • @xdraxulisx 重读答案。都写的够清楚了。
  • 经过一番阅读:我想你的意思是我应该在头文件中定义struct。我想过这个,其实我也想过创建一个只有头文件的库,但是这不会增加很多开销吗?我在某处读到过,我需要尽可能高的性能。
  • @xdraxulisx Yes> 我在回答中写道,您必须将结构定义放在标题中。
  • 感谢您的编辑,现在清晰多了!
猜你喜欢
  • 2012-02-16
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多