gpt4 book ai didi

c - 前向声明错误我无法理解

转载 作者:太空宇宙 更新时间:2023-11-04 03:44:27 25 4
gpt4 key购买 nike

头文件声明:

    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 语言处理多个文件和头文件,所以我真的很难理解这些错误。任何帮助都会很棒,谢谢!!

最佳答案

你把结构定义放到一个c文件中。这不是它的工作方式:您需要将定义放入标题中。

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

如果您想将struct 的详细信息保密,请将其放入私有(private)头文件中。也包括来自私有(private)头文件的公共(public)头文件:

队列.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;
};

主.c:

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

现在您的项目应该可以正常编译了。

关于c - 前向声明错误我无法理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25925247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com