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

Googleのために"不完全なタイプ"。 – wildplasser

+0

typedefでコードを難読化するのではなく、構造体を使用するための1つの議論があります。 –

答えて

3

あなたのアプローチの問題点は、a_tためtypedefb.h、およびその逆であるということです。

ややきれいな方法は、このように、宣言であなたのstructと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 
関連する問題