當您在評論中指出,就包含在test.h
a.h
和反之亦然。由於循環依賴,也被稱爲交叉包含,這引入錯誤作爲「未定義」的函數和類。
在你的情況下,當.cpp
文件包括test.h
,它首先包括a.h
和然後定義函數anything();
,這顯然不是你想要的,處理a.h
時,因爲anything()
是不確定的。
你的代碼擴展到與此類似,編制包括test.h
(a.h
前)的單位,其本身包括a.h
任何事情之前的時候:
/* INCLUDED FROM a.h */
class Fooness{
public:
Fooness(){
anything();
};
};
inline void anything() {
....
}
正如你看到的,有沒有anything()
定義當你使用它。但是,如果編譯單元包括a.h
(test.h
之前),其本身包括test.h
,它擴展爲這樣的事情:
/* INCLUDED FROM test.h */
inline void anything() {
....
}
class Fooness{
public:
Fooness(){
anything();
};
};
這樣的順序是正確的。
,使其在這兩種情況下工作,你可以在向前test.h
,申報anything()
你包括a.h
前:
修正test.h版本:
#ifndef TEST_H
#define TEST_H
void anything(); // forward-declaration
#include "a.h" // <-- this is important to be *below* the forward-declaration
inline void anything() {
....
}
// more stuff
#endif
然後,當包括test.h
(在a.h
之前)時,它擴展到以下內容:
void anything();
/* INCLUDED FROM a.h */
class Fooness{
public:
Fooness(){
anything();
};
};
inline void anything() {
....
}
is.h包含在test.h中? – leemes
取消我的評論,leemes已經全部結束了。= P – WhozCraig
@ lemes是的。 – johnbakers