2012-04-12 164 views
2

我有这个循环依赖的问题C,我环顾了这个主题的其他问题,但实际上找不到答案。C循环依赖

我有这样的第一个结构命名顶点:

#ifndef MapTest_vertex_h 
#define MapTest_vertex_h 

#include "edgelist.h" //includes edgelist because it's needed 

typedef struct 
{ 
    char* name; 
    float x, y; 
    edgelist* edges; 
} vertex; 

#endif 

第二结构是通过该顶点包含在EdgeList都。

#ifndef edgelist_h 
#define edgelist_h 

#include "edge.h" //include edge, because its needed 

typedef struct _edgelist 
{ 
    edge** edges; 
    int capacity, size; 
} edgelist; 

//... 

#endif 

然后最后一个结构,问题引发的结构,边缘结构被边界列表包含在上面。

#ifndef MapTest_edge_h 
#define MapTest_edge_h 

#include "vertex.h" //needs to be included because it will be unkown otherwise 

typedef struct 
{ 
    float weight; 
    vertex* destination; 
    int found; 
} edge; 

#endif 

我试图尽我所能,向前声明,使用#ifndef#define等,但未能找到答案。

我该如何解决这个循环依赖问题?

+0

在C11,你可以重复无害的typedef。你可以在任何或所有头文件中编写'typedef struct edge edge;''''typedef struct vertex vertex;' - 'typedef struct edgelist edgelist;'然后只需定义结构类型信息(不带'typedef'前缀或名称在结尾处):'struct vertex {...};' - 'struct edge {...};' - 'struct edgelist {...};'。但是这不适用于C99或C90;在早期版本的C中定义一个'typedef'是错误的。 – 2017-03-07 22:05:52

回答

8

似乎你应该不需要在任何文件中包含任何东西。相关类型的向前声明应该是足够了:

#ifndef MapTest_vertex_h 
#define MapTest_vertex_h 

struct edgelist; 

typedef struct 
{ 
    char* name; 
    float x, y; 
    edgelist* edges; // C++ only - not C 
} vertex; 

#endif 

等在C编码,你必须写:

struct edgelist; 

typedef struct 
{ 
    char* name; 
    float x, y; 
    struct edgelist* edges; 
} vertex; 
1

我假设一个顶点需要知道什么边缘连接到它,边缘需要知道它连接的顶点。

如果是对我,我会创建单独的数据类型的顶点和边关联:

struct vertex { 
    char *name; 
    float x, y; 
}; 

// edgelist as before 

struct edge { 
    float weight; 
    int found; 
}; 

// New struct to map edges and vertices 

struct vertexEdge { // you can probably come up with a better name 
    struct vertex *v; 
    struct edgelist *edges; 
}; 

// New struct to map vertices and edges 

struct edgeVertext { 
{ 
    struct edge *e; 
    struct vertex *vertices; 
}; 

我对睡眠的运行一周大约10-12小时的后面,所以我很确定有更好的方式来设计映射类型(可能不需要多于一种类型),但这是我所采用的一般方法。

2

这种依赖关系使用正向声明中断。相反,包括与结构的完整定义的文件,有两种选择:

1.

typedef struct 
{ 
    char* name; 
    float x, y; 
    struct _edgelist* edges; /* add "struct" here (elaborated type specifier) */ 
} vertex; 

2.

struct __edgelist; /* better form: forward declaration */ 

typedef struct 
{ 
    char* name; 
    float x, y; 
    struct _edgelist* edges; /* still need to add "struct" here */ 
} vertex; 
+0

请注意,以下划线开头并且后面跟着另一个下划线或大写字母的符号被无条件地保留以供'执行'使用。通常,避免创建以下划线开头的名称。 – 2017-03-07 21:59:00