【问题标题】:C++ not compiling because its say the file doesn't exist but it is in the same directory [duplicate]C ++没有编译,因为它说文件不存在但它在同一个目录中[重复]
【发布时间】:2017-01-13 17:01:28
【问题描述】:

在一个文件夹中,我得到了以下文件:

book.h、book.cpp、card.h、card.cpp

这些是本书的内容。h

class book {

public:
        string title;
        string author;
        string get_title();
        string get_author();

}

book::book(string title, string author){
   title = title;
   author = author;
}

这是我的 book.cpp:

#include <book.h>
#include <iostream>
#include <string>

using namespace std;

string book::get_title(){

  return title;
}

string book::get_author(){
 return author;
}

int main(){

cout << ¨it works! \n¨ 
}

我尝试使用 g++ -c book.cpp 进行编译,我不断收到一条错误消息:

book.cpp:1:18:致命错误:book.h:没有这样的文件或目录 编译终止。

【问题讨论】:

  • 用户包含应该在""而不是&lt;&gt;
  • 不是答案,但是...无论如何,您的 book.h 看起来都是错误的。您需要使用 std::string 并在标题中包含
  • 这段代码还有其他一些问题。 book.h 应该是 #include &lt;string&gt;,并且有 std::string。整个而不是string。永远不要这样做using namespace std,这是个坏主意。 title = title; 没有做你认为的事情。拥有公共数据成员违背了访问者的目的。
  • 你为什么要为一个明显的 C++ 问题向 C 标签发送垃圾邮件?
  • 看我不知道好不好?我是新手,很抱歉造成混乱

标签: c++ compiler-errors g++ header-files


【解决方案1】:

两者的区别

#include <book.h>

#include "book.h"

是第一个仅在 INCLUDE 路径中查找文件book.h。后者首先在源文件所在的目录中查找文件,如果找不到,则在 INCLUDE 路径中查找。 因此,您可以通过用引号替换尖括号或将目录添加到 INCLUDE 来解决您的问题。你可以通过这样编译来做到这一点

g++ -I . -c book.cpp

【讨论】:

    【解决方案2】:

    #include 语句在包含的文件是“包含”路径的一部分时使用 &lt;&gt; 括号,通常(但不限于)当文件来自库或 C++ 标准库时。

    "" 用于代替项目本地文件和源代码本地文件。

    如果你把它们混在一起,你会过得很糟糕。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-01
      • 2020-10-31
      • 1970-01-01
      • 2023-03-22
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多