【问题标题】:struct error in defining struct in one header file, and using it in another在一个头文件中定义结构并在另一个头文件中使用它时出现结构错误
【发布时间】:2013-04-15 14:04:32
【问题描述】:

我有 4 个文件 = pic.h、main.c、framehandle.c 和 framehandle.h

pic.h 和 framehandle.h 都包含在我的主目录中:

#include "pic.h"
#include "framehandling.h"

pic.h 具有以下结构定义。

struct f
{
    unsigned sleep : 1;
    unsigned push  : 1;
    unsigned rx    : 1;
    unsigned tx    : 1;
    unsigned validPacket : 1;
};

我在我的 main.c 文件中使用

声明了这个结构
struct f flag; 

当我尝试在 framehandle.c 中使用它时,我得到一个我理解的未声明的错误。

为了解决这个问题,我在 framehandle.h 中添加了以下内容:

extern struct f flag;

但是编译器仍然抱怨没有在 framehandle.c 中声明标志

我做错了什么? 不会 extern struct f 标志;应该告诉编译器在其他地方寻找声明? 将它放在主题标题中不是正确的位置吗?

--编辑--

我正在添加包含文件和变量声明的序列

#include "pic.h"
#include "framehandling.h"

struct f flag;

void main(void)
{ }

【问题讨论】:

  • framehandle.c 是否包含 pic.h?确切的编译器错误是什么?
  • framehandle.c 确实包含 pic.h。确切的编译器错误是#framehandling.c:97: error: 'flag' undeclared (first use in this function)
  • 也许是个愚蠢的问题,但framehandle.c 是否包含framehandle.h
  • @BryanOlivier 是的,Bryan 确实如此
  • 然后尝试查看framehandle.c 的预处理器输出(gcc 的选项-E),看看它是否确实包含extern struct f flag 声明。你的main.c 提到framehandling.h 而你的文本的其余部分提到framehandle.h

标签: c


【解决方案1】:

这取决于您是否在 main.c 中将 struct f flag; 声明为全局或本地。如果在函数内部声明它,则必须将声明移到函数外部。

【讨论】:

  • Struct f 标志被声明为全局
  • @Volcano 是在使用的地方之前还是之后声明的?
  • 我刚刚意识到您正在头文件中添加外部定义。您可以将 extern 移动到您的 C 源代码并检查错误吗?另外,您使用哪个编译器?如果是 gcc,您可以使用 -E 选项检查您的预处理器如何包含定义。
  • 我想是之后?我不确定,我将编辑我的问题以包括我的#includes 和变量 decleration。
  • @unxnut 将其放在 C 文件中会导致无用的变量减元错误
【解决方案2】:

问题的解决方案是 extern struct f 标志应该在 pic.h 中。从某种意义上说,把它放在声明之后。我还要感谢大家的意见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多