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

时间:2016-01-06 15:01:31

标签: c compiler-errors typedef

目录包含以下文件:

  1. "车"文件:
  2. 一个。 car.h:

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

    湾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)
    ...
    

    ℃。 car_main.c

    #include <stdio.h>
    #include "car.h"
    
    int main()
    {
       ...
       (some tests)
       ...
    }
    

    2。 &#34;车辆&#34;文件:

    一个。 vehicles.h

    #ifndef __VEHICLES_H__
    #define __VEHICLES_H__
    
    typedef struct vehicles vehicles_t;
    
    ...
    (some functions declarations)
    ...
    
    #endif /* ifndef __VEHICLES_H__ */  
    

    湾vehicles.c

    #include <stdio.h>
    #include "car.h"
    #include "vehicles.h"
    
    struct vehicles
    {
       car_t carlist;
       void *data; 
    };
    

    ℃。 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中的typedef car_t,如果car.h中包含car.h?

1 个答案:

答案 0 :(得分:2)

问题是在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;

{{1}}
相关问题