【发布时间】: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 <string>。
在每个头文件中,无论我在哪里使用 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