【问题标题】:Circular header dependency循环头依赖
【发布时间】:2018-01-04 15:22:23
【问题描述】:

我被困在(我认为是)VS2017 c 编码中的循环依赖问题。

我尝试查找问题,并在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.ctrip.c 文件仅包含 #include "travelers.h"/#include "trip.h"

错误只发生在trip.hTraveler *travelers;:

我不知道如何解决这个问题。

This 看起来像同样的问题,但我无法将其转换为我的代码。

任何帮助都可以得到。

【问题讨论】:

标签: c visual-studio circular-dependency


【解决方案1】:

这里没有循环。

如果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

【讨论】:

  • ...按照先travelers.h然后trip.h的顺序,这样Traveler在用于Trip之前是已知的。
  • 我在我的代码中实现了这一点,包括对 calloc() 转换的更改,但它仍然给我同样的错误。我编辑了问题中的代码。
  • @NoëlVissers:你做了 rebuild 吗?
  • @alk 对不起。完全忘记了这一点。我通常不在 c 或 VS 中编程。但现在它起作用了。非常感谢先生!
【解决方案2】:

作为备注,错误是由typedef 引起的。 C 接受 opaque 结构,前提是您不需要它们的实现细节:

啊哈:

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;
};

b.c

#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 上一无所知除了它是一个结构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-11
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 2011-06-16
    • 2015-07-25
    相关资源
    最近更新 更多