繁体   English   中英

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

[英]using struct typedef in multiple .c & .h files

目录包含以下文件:

  1. “汽车”文件:

一种。 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)
...

C。 car_main.c

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

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

2.“车辆”文件:

一种。 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; 
};

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM