我坚持(我认为)在VS2017编码中的循环依赖问题。
我试着查找问题,并在stackoverflow上发现了很多类似的问题,但我似乎无法通过这些问题解决我的问题。
我的代码:
main.c中
#include <stdio.h>
#include "travelers.h"
#include "trip.h"
int main(void) {
int nTravelers = 0;
int nTrips = 0;
Traveler *travelersArray = (Traveler*)calloc(nTravelers, sizeof(Traveler));
Trip *tripsArray = (Trip*)calloc(nTrips, sizeof(Trip));
return 0;
}
travelers.h
typedef struct {
unsigned int id;
char *name;
char *adress;
char *residence;
} Traveler;
trip.h
typedef struct {
unsigned int id;
char *touringCar;
char *destination;
char *date;
Traveler *travelers;
unsigned int amount;
} Trip;
travelers.c
和trip.c
文件只包含#include "travelers.h"
/ #include "trip.h"
该错误仅发生在trip.h
的Traveler *travelers;
:
我不知道如何解决这个问题。
This看起来像是同样的问题,但我无法将其转换为我的代码。
任何帮助表示赞赏。
这里没有周期。
如果trip.c
包括trip.h
,则还应包括travelers.h
,因为它的定义(Trip
)取决于后者(Traveller
)。
知道这一点,可以将travelers.h
纳入trip.h
。尽管如此,这使事情变得复杂,所以首先添加到每个标头是一个好主意,因此调用标头保护,以防止在预处理器级别上出现重复定义。
这样做使标题看起来像这样:
travelers.h
#ifndef TRAVELERS_H
#define TRAVELERS_H
typedef struct {
unsigned int id;
char *name;
char *adress;
char *residence;
} Traveler;
#endif // #ifndef TRAVELERS_H
trip.h
#ifndef TRIP_H
#define TRIP_H
#include "travelers.h" // makes including it unnecessary where trip.h is included
typedef struct {
unsigned int id;
char *touringCar;
char *destination;
char *date;
Traveler *travelers;
unsigned int amount;
} Trip;
#endif // #ifndef TRIP_H
作为评论,错误是由typedef
引起的。如果您不需要它们的实现细节,C接受不透明的结构:
啊:
struct A {
int aVal;
const char * astr;
};
交流转换器:
#include "a.h"
const char *getAStr(struct A*a) {
return a->astr;
}
b.h
const char *getName(struct B*);
struct B {
int bVal;
struct A *a;
};
公元前
#include "b.h"
const char *getAStr(struct A*);
const char * getName(struct B* b) {
return getAStr(b->a);
}
main.c中
#include <stdio.h>
#include "a.h"
#include "b.h"
int main() {
struct A a = { 1, "foo" };
struct B b = { 2, &a };
printf("%d - %d : %s\n", b.bVal, b.a->aVal, getName(&b));
return 0;
}
在b.c中编译和链接甚至没有警告。在struct A
上没有什么是已知的,除了它是一个结构。