C循环依赖

Mar*_* R. 4 c circular-dependency include c-preprocessor

我在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
Run Code Online (Sandbox Code Playgroud)

第二个结构是顶点包含的边缘列表.

#ifndef edgelist_h
#define edgelist_h

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

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

//...

#endif
Run Code Online (Sandbox Code Playgroud)

然后是最后一个结构,即问题引发的结构,边结构包含在上面的edgelist中.

#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
Run Code Online (Sandbox Code Playgroud)

我试着尽我所能,向前声明,使用#ifndef,#define等等,但找不到答案.

如何解决此循环依赖问题?

And*_*nck 10

看起来你不应该在任何文件中包含任何内容.有关类型的前瞻性声明应该足够:

#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
Run Code Online (Sandbox Code Playgroud)

在C编码中,你必须写:

struct edgelist;

typedef struct
{
    char* name;
    float x, y;
    struct edgelist* edges;
} vertex;
Run Code Online (Sandbox Code Playgroud)