我对C中的头文件有一个疑问。假设我有一个头文件,其中包含一个名为的结构汽车cars.h
,如下所示:
typedef struct car_s {
string plate;
string model;
} car;
现在,我有另一个头文件,其中包括上述头文件,称为drivers.h
,如下所示:
#include "cars.h"
typedef struct driver_h
{
string id;
string name;
car own_car;
} driver;
现在,假设我有另一个文件,但这一次是一个C文件,名为main.c
,如下所示:
#include "cars.h"
#include "drivers.h"
int main() {
car c;
driver bob;
bob.own_car = c;
return 0;
}
您能否解释为什么这是错误的,我该怎么做以防止出现任何错误?
谢谢!
问题是同一头文件可能被多次包含。如何防止在代码中多次包含相同的头文件?您可以将其添加到头文件中:
对于cars.h
:
#ifndef CARS_H
#define CARS_H
typedef struct car_s{
stringplate;
string model;
}car;
#endif
这将检查此头文件是否已经包含,如果不再包含,则现在将包含它。
您也可以这样做drivers.h
:
#ifndef DRIVERS_H
#define DRIVERS_H
#include "cars.h"
typedef struct driver_h
{
string id;
string name;
car own_car;
}
#endif
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句