2012-02-23 85 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