2013-10-08 18 views
0

我的問題類似於this one但我無法確定如何在eclipse中修復它。GCC無法自動從.h類解析.cpp包括

在eclipse上編譯一個小程序時,我有一個奇怪的行爲。當我將.cpp文件包含在頭部的末尾(並且將.h包含在.cpp中)時,它會進行編譯,否則就不會。

我試圖包含的類是在一個單獨的項目中,並且該項目已正確鏈接。

下面是一個例子:

在項目源

文件myclass.h

#ifndef MYCLASS_H_ 
#define MYCLASS_H_ 

namespace lol 
{ 
class myclass{ public // definitions... } 
} 
//#include myclass.cpp //**works when I uncomment this** 
#endif 

文件myclass.cpp

#include "myclass.h" // ** does not work unless I include my .cpp (unity build like) ** 
        // and I don't want to include .cpp files 
namespace lol{ // not funny 

myclass::myclass(){ 
} //code ... code 
} 

在其他項目 mainFile.cpp

#include "myclass.h" // works only if I include myclass.cpp at the end of myclass.h 

using namespace lol; 
int main(){ 
    myclass obj = myclass(); // gives undefined reference to lol::myclass::myclass() 
} 

我可以通過建立一切從一個makefile這是我喜歡的一個解決方案解決這個問題,但我需要使用Eclipse,可悲。

有什麼建議嗎?

謝謝!

+2

請閱讀gcc介紹和翻譯單元是什麼以及什麼是鏈接和它的全部功能。並且從不包含.cpp文件。 – PlasmaHH

+0

沒有任何與您引用的問題類似。你應該真的按照@ PlasmaHH的建議! –

+0

關於從不包含.cpp,我確實想避免它。我知道什麼是鏈接,我可以使用makefile,這是關於在eclipse中做的。你應該閱讀這個http://stackoverflow.com/questions/543697/include-all-cpp-files-into-a-single-compilation-unit – Johnride

回答

1

您在包含文件末尾缺少「#endif」。

改爲使用「#pragma once」。

// .h file 
#pragma once 

namespace lol 
{ 
    class foo {}; 
} 

// end of file 

查看我對彙編單元和管道的解釋here

+0

抱歉,我忘記在我的問題中編寫endif,它存在於我的代碼中。謝謝你回答這個問題。 – Johnride

+0

您需要更新帖子才能包含您遇到的實際編譯/鏈接錯誤 – kfsone

0

我想說,如果你從eclipse auto makefile生成中看到你的.cpp,它將它作爲源(翻譯單元)並將其添加到源列表中。

如果要包含內聯定義(一次),則應使用不同的文件擴展名(例如.tcc,.icc)。

您也可以嘗試從項目的資源配置中排除它(右鍵單擊.cpp,選擇'資源配置 - >從構建中排除')。

另一種選擇是將項目類型更改爲「Makefile項目」並自行維護makefile。