前方声明错误我无法理解

时间:2014-09-19 02:05:07

标签: c struct typedef header-files forward-declaration

头文件声明:

    typedef struct Queue *QueueP;

C文件实现:

    struct Queue
    {
      char *head;
      char *tail;
      QueueItemT item; //char typedef from the header file, not what's giving error
      int SizeL;
      int sizeP;
      int QueueSize;
    };

C主文件:

    #include <stdio.h>
    #include <stdlib.h>
    #include "Queue1.h"

    int main()
    {   
      struct Queue queue;
      QueueP myQueue = &queue;
      return 0;
    }

我分别在以下行中收到错误消息:

    struct Queue queue;
                 ^
                 Main : variable has incomplete type 'struct Queue'

    typedef struct Queue *QueueP;
                   ^
                   Header : note: forward declaration of 'struct Queue'

知道可能导致这些错误的原因是什么?我是在C中使用多个文件和头文件的新手,所以我真的无法解决这些错误。任何帮助都会很棒,谢谢!!

2 个答案:

答案 0 :(得分:1)

您将结构定义放入c文件中。这不是它的工作原理:您需要将定义放入标题中。

这是因为struct的定义不是一个实现。 C编译器需要此信息才能正确处理struct的声明。前向声明允许您定义指向struct的指针;声明struct本身需要一个完整的定义。

如果您想保留struct私有的详细信息,请将其放入私有标头文件中。还要包含私有标头中的公共标头文件:

queue.h

typedef struct Queue *QueueP;

queue_def.h

#include "queue.h"
struct Queue
{
  char *head;
  char *tail;
  QueueItemT item; //char typedef from the header file, not what's giving error
  int SizeL;
  int sizeP;
  int QueueSize;
};

main.c中:

#include <stdio.h>
#include <stdlib.h>
#include "queue_def.h"

现在你的项目应该没有问题地编译。

答案 1 :(得分:0)

实际上,我提出声明问题的原因是因为我试图从主文件中访问结构(在.c文件中声明)。

这不仅是一个糟糕的编程实践,项目的理想特征是最终用户(即使用界面和实现来构建他们的'main.c'文件的人)应该不知道什么样的结构是在使用时,他们应该能够构建一个具有给定功能的队列,而不知道幕后发生了什么。

D'哦!!!