【问题标题】:Error: unknown type in C. What can be the reason when all required header files are included?错误:C 中的未知类型。包含所有必需的头文件时可能是什么原因?
【发布时间】:2026-01-12 03:55:01
【问题描述】:

所以我无法弄清楚以下问题: 我得到了 orderPtr 的未知类型,它是 struct Order 的 typedef,即使我已经包含了声明这种类型的头文件。 这是queue.h中的代码:

#ifndef QUEUE_H
#define QUEUE_H

#include <stdio.h>
#include "book.h"
#include "queue_node.h"

/*
 * Queue structure for consumers threads
 */
typedef struct queue {
    pthread_mutex_t mutex;
    pthread_cond_t notempty;
    struct queue_node *rear;
} queuePtr;

void queue_enqueue(queuePtr *, orderPtr *);

orderPtr *queue_dequeue(queuePtr *queue);


#endif

这里这个类型是在 book.h 中声明的:

#ifndef BOOK_H
#define BOOK_H

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <pthread.h>
#include "uthash.h"
#include "customer.h"
#include <errno.h>
#include <unistd.h>
#include "queue.h"

typedef struct order {
    char *title;
    double price;
    char *idnum;
    char *category;
} orderPtr;

void order_destroy(orderPtr *);
orderPtr * order_create(char *, double, char *, char *);

#endif

【问题讨论】:

  • 你有一个循环引用,book.h 包括queue.hqueue.h 包括book.h。我不太确定您希望编译器对此做什么:)
  • @JoachimIsaksson 谢谢!我真的不知道
  • 这部分结构定义:'} queuePtr;'不是生成指向结构类型的指针,而是生成结构类型。您可以将行更改为: '} *queuePtr; --或者-- 你可以调用函数: void order_destroy(orderPtr *);使用 order_destroy( &myOrder );其中 myOrder 是结构的实例
  • 在链表中,指向链表中下一个条目的指针应该是与结构本身相同类型的结构,所以这一行: struct queue_node *rear;应该是:struct queue *rear;

标签: c


【解决方案1】:

如果你遵循包含链,是这样的:

  1. main.c 包括 book.h
  2. book.h 在顶部包含queue.h(在orderPtr 的typedef 之前)
  3. queue.h 尝试使用尚未 typedef 的 orderPtr = 错误
  4. 终于来了orderPtr的typedef。

您可以通过多种方式解决此问题。一种方法是在queue.h 你可以这样做:

/*
 * Queue structure for consumers threads
 */
typedef struct queue {
    pthread_mutex_t mutex;
    pthread_cond_t notempty;
    struct queue_node *rear;
} queuePtr;

struct orderPtr;  // Forward declaration

// The use of struct orderPtr * is allowed because it is a pointer.
// If it wasn't a pointer, it would be an error because the size
// would be unknown.
void queue_enqueue(queuePtr *, struct orderPtr *);

struct orderPtr *queue_dequeue(queuePtr *queue);

【讨论】:

    最近更新 更多