2012-02-23 172 views
0

我有循环依赖的代码。解决循环typedef依赖性的正确方法是什么?

老A.H文件:

#ifndef A_H 
#define A_H 

#include "b.h" 

typedef struct { 
    b_t *test; 
} a_t; 

#endif 

老b.h文件:

#ifndef B_H 
#define B_H 

#include "a.h" 

typedef struct { 
    a_t *test; 
} b_t; 

#endif 

我只是想知道,如果我的解决方案是 “适当的方式” 来解决这个问题。我想生成漂亮而清晰的代码。

新A.H文件:

#ifndef A_H 
#define A_H 

#include "b.h" 

typedef struct b_t b_t; 

struct a_t { 
    b_t *test; 
}; 

#endif 

新b.h文件:

#ifndef B_H 
#define B_H 

#include "a.h" 

typedef struct a_t a_t; 

struct b_t { 
    a_t *test; 
}; 

#endif 
+0

谷歌的“不完整的类型”。 – wildplasser 2012-02-23 11:38:06

+0

有一个参数用于使用结构而不是使用typedefs混淆代码。 – 2012-02-23 13:19:09

回答

3

与方法的问题是,对于typedefa_tb.h,反之亦然。

一个稍微清洁的方式将让您的typedef与结构,并利用结构标签的声明,就像这样:

#ifndef A_H 
#define A_H 

struct b_t; 

typedef struct a_t { 
    struct b_t *test; 
} a_t; 

#endif 

BH

#ifndef B_H 
#define B_H 

struct a_t; 

typedef struct b_t { 
    struct a_t *test; 
} b_t; 

#endif