2012-01-05 134 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. 

或任何你的文件...