2012-01-05 140 views
1

我正在從Java遷移到C++。看來C++使得在不同文件中聲明類是很困難的。所以,我需要你的幫助,g ++找不到頭文件

在我的main.cpp:

#include "Sphere.h" 

using namespace std; 
..... 
... 
.. 

int main(void) { 
    Sphere *earth = new Sphere(sphere_start ,sphere_end); 
... 
.. 
. 

在我Sphere.h

class Sphere 
{ 

    public: 
     Sphere(int,int); 

} 

,並在我的Sphere.cpp

#include "Sphere.h" 

using namespace std; 

int sphere_start, sphere_end; 

Sphere::Sphere (int a, int b) 
{ 
    sphere_start = a; 
    sphere_end = b; 
} 

void Sphere::render(int i) 
{ 
    .... 
    .. 
    . 

} 

這是我認爲非常基本的代碼會導致以下錯誤:

main.cpp:14:20: fatal error: Sphere.h: No such file or directory 
compilation terminated. 

爲什麼?

回答

3

Sphere.h必須與包含它的每個文件位於同一目錄中,或者必須指向編譯器以搜索Sphere.h所在的目錄。

+0

所有文件在同一目錄 – 2012-01-05 00:38:50

+0

遺憾的文件是不是在同一個目錄。大聲笑愚蠢我 – 2012-01-05 00:45:11

+0

如何可以「調試」這個問題,當清楚所有頭文件都已到位,所有必要的開發包安裝和源文件引用正確的頭文件路徑,但編譯器仍然無法找到頭文件。 – 2014-01-10 20:28:20

1

兩個潛在的錯誤:

  • 是Sphere.h在同一目錄下的main.cpp?
  • 是Sphere.h命名爲Sphere.h而不是sphere.h?
2

你應該發佈你的命令行,但我的猜測是你應該把頭文件的路徑告訴編譯器。如果您使用的Linux試試這個:

g++ main.cpp shpere.cpp -I<path_to_Sphere.h> -o main 
5

您需要的路徑添加到您的編譯命令到頭文件中可以找到。

如果你的頭在headers目錄添加-Iheaders

g++ -o main.o -c -Iheaders main.cpp 
g++ -o sphere.o -c -Iheaders sphere.cpp 
g++ -o app main.o sphere.o -L. 

或任何你的文件...