【问题标题】:fatal error: string: No such file or directory compilation terminated致命错误:字符串:没有此类文件或目录编译终止
【发布时间】:2012-02-03 10:18:23
【问题描述】:

我已经苦苦挣扎了 3 个多小时,但找不到解决方案。 一个简单的 helloworld 程序运行良好,我可以得到输出,

 #include<iostream>
    #include<string>

    using namespace std;
    int main(){
       string s;
       cout<<"hello world";
    }

但是对于我的数独项目,我有以下用户定义的标题 文件、SudokuSolver.h、Matrix.h、Cell.h、Pos.h、Error.h、Exception.h 和 它们对应的 .cpp 文件。

ExampleProgram.cpp 使用这些头文件,来解决数独问题。

(所有 .h 和 .cpp 文件都在同一个文件夹中。)

我已包含using namespace std;,并将字符串包含为#include &lt;string&gt;。 在每个头文件中,无论我在哪里使用 string.h。但即使我在运行时得到fatal error: string: No such file or directory compilation terminated.

g++ ExampleProgram.cpp SudokuSolver.h Cell.h Error.h Pos.h Matrix.h

当我将 ExampleProgram.cpp 编译为

 g++ -c ExampleProgram.cpp SudokuSolver.h
 Cell.h Error.h Pos.h Matrix.h       

我没有收到任何错误。

当我使用 ./a.out 运行 ExampleProgram.cpp 时,我没有得到我的数独求解器的输出。相反,我得到了我之前运行的 helloworld 程序的输出。它显示我的ExampleProgram.cpp 没有成功编译。不过如前所述

g++ -c ExampleProgram.cpp  SudokuSolver.h 
    Cell.h Error.h Pos.h Matrix.h       

没有给出任何错误。

这是我的输出:

[fosslab@fosslab SudokuSolver]$ g++ -c Error.h
[fosslab@fosslab SudokuSolver]$ g++ -c Exception.h
[fosslab@fosslab SudokuSolver]$ g++ -c Matrix.h
[fosslab@fosslab SudokuSolver]$ g++ -c Cell.h
[fosslab@fosslab SudokuSolver]$ g++ -c Pos.h
[fosslab@fosslab SudokuSolver]$ g++ -c SudokuSolver.h
[fosslab@fosslab SudokuSolver]$ g++ -c ExampleProgram.cpp SudokuSolver.h Excepti
on.h Cell.h Error.h Pos.h Matrix.h                                             
[fosslab@fosslab SudokuSolver]$ ./a.out
hello world[fosslab@fosslab SudokuSolver]$ 

【问题讨论】:

  • 你不编译头文件。
  • @trojanfoe 我已经编译过了。
  • @EAGER_STUDENT 不,实际上你从不编译头文件。当您编译(实际上是在预处理阶段)一个 .cpp 文件时,它会使用 include 语句包含在内。
  • 你不应该编译,头文件应该只包含函数/类的声明而不是它们的定义(唯一的例外是内联函数和模板)。在你编译源文件(不是头文件)之后,你将把它全部链接起来,linker 检查所有需要的声明是否有正确的定义(如果没有,你会得到Unknown reference...)。
  • @Vyktor:你的意思是它们应该只包含函数声明和类定义。

标签: c++ string g++ header-files


【解决方案1】:

我知道它已经晚了,但我的回答可能会帮助其他面临这个问题的人。您的系统上很可能没有 libstdc++-devel 软件包。 请重新检查。我遇到了同样的问题,可以通过安装 devel 包来解决。

【讨论】:

    【解决方案2】:

    首先,头文件意味着包含在源文件中。不要将它们添加到编译器的命令行中。

    其次,g++ 的命令行参数“-c”告诉 g++ 不要链接和制作可执行文件,而只制作目标文件。

    你应该这样做:

    $ g++ -c ExampleProgram.cpp
    $ g++ ExampleProgram.o
    

    $ g++ ExampleProgram.cpp
    

    在上述两种情况下,您都会得到一个新的“a.out”可执行程序。

    如果你有多个 source 文件,那么编译它们而不是头文件:

    $ g++ -c Error.cpp
    $ g++ -c Exception.cpp
    $ # etc...
    $ g++ -c ExampleProgram.cpp
    $ g++ Error.o Exception.o ... ExampleProgram.o
    

    【讨论】:

      猜你喜欢
      • 2012-08-21
      • 2012-10-19
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多