C循环依赖 [英] C circular dependency
问题描述
我在 C 中遇到循环依赖的问题,我查看了有关此主题的其他问题,但实际上找不到答案。
I have this problem with circular dependency in C, I looked around the other questions about this topic but really couldn't find the answer.
我有第一个名为vertex的结构:
I have this first struct named 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
第二个结构是边缘列表,包含在vertex。
The second struct is the edgelist which is included by the vertex.
#ifndef edgelist_h
#define edgelist_h
#include "edge.h" //include edge, because its needed
typedef struct _edgelist
{
edge** edges;
int capacity, size;
} edgelist;
//...
#endif
然后是最后一个结构,即问题引发的结构,边结构包含在上面的边缘列表中。
And then the last struct, the one where the problem raises, the edge struct gets included by the edgelist above.
#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
等,但找不到答案。
I tried everything I could, forward declaring, using #ifndef
, #define
etc. but couldn't find the answer.
如何解决这个循环依赖问题?
How can I resolve this circular dependency problem?
推荐答案
似乎就像你不应该在任何文件中包含任何内容。相关类型的远期声明应该足够:
Seems like you shouldn't need to include anything in any of the files. A forward declaration of the relevant types should be sufficient:
#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编码中,你必须写:
etc. In C coding, you have to write:
struct edgelist;
typedef struct
{
char* name;
float x, y;
struct edgelist* edges;
} vertex;
这篇关于C循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!