在多个 .c 和 .h 文件中使用 struct typedef

using struct typedef in multiple .c & .h files

一个目录包含以下文件:

  1. "car" 个文件:

一个。 car.h:

#ifndef __CAR_H__
#define __CAR_H__

typedef struct car car_t;
...
(some functions declarations)
...
#endif /* __CAR_H__ */

b。 car.c

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

typedef struct car_node
{
   void *data;
   struct car_node *next;
   struct car_node *prev;
} car_node_t;

struct car
{
   car_node_t head;
   car_node_t tail;
};
...
(some functions implementations)
...

c。 car_main.c

#include <stdio.h>
#include "car.h"

int main()
{
   ...
   (some tests)
   ...
}

2。 "vehicles" 个文件:

一个。 vehicles.h

#ifndef __VEHICLES_H__
#define __VEHICLES_H__

typedef struct vehicles vehicles_t;

...
(some functions declarations)
...

#endif /* ifndef __VEHICLES_H__ */  

b。 vehicles.c

#include <stdio.h>
#include "car.h"
#include "vehicles.h"

struct vehicles
{
   car_t carlist;
   void *data; 
};

c。 vehicles_main.c

#include <stdio.h>
#include "car.h"
#include "vehicles.h"

int main()
{
   ...
   (some tests)
   ...
}

使用 makefile 编译以下内容时,一切正常: car.c, car_main.c.

但是当我用 makefile 编译以下文件时:car.c、vehicles.c、vehicles_main.c,我得到以下错误:

vehicles.c: error: field ‘carlist’ has incomplete type

我的问题是:如果 car.h 包含在 vehicles.c 中,为什么编译器无法识别在 car.h 中找到的 typedef car_t?

问题是在 vehicles.c 内部,编译器需要知道 car_t 实际上 是什么 ,而您只提供了它的内容应该称为。什么car_t实际上car.c中定义的。要解决此问题,您要么必须使 carlist 成为指针(因为编译器不需要完整的类型),要么必须将结构定义移动到 .h文件:

car.h:

typedef struct car_node
{
    void *data;
    struct car_node *next;
    struct car_node *prev;
} car_node_t;

typedef struct car {
    car_node_t head;
    car_node_t tail;
} car_t;