C循环依赖
我在C中有循环依赖这个问题,我查看了关于这个主题的其他问题,但实际上找不到答案。
我有第一个名为vertex的结构:
#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
第二个结构是顶点包含的边缘列表。
#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
, #ifndef
#define
等,但找不到答案。
如何解决此循环依赖问题?
好像你不应该在任何文件中包含任何内容。 有关类型的前瞻性声明应该足够:
#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。
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;
我假设一个顶点需要知道哪些边连接到它,并且边需要知道它连接到哪个顶点。
如果由我决定,我会创建单独的数据类型来关联顶点和边:
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个小时,所以我很确定有更好的方法来设计映射类型(可能以不需要多种类型的方式),但这是我采取的一般方法。