【发布时间】:2016-07-09 02:56:48
【问题描述】:
以下是我的 C++ 程序:
main.cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream fileWriter;
fileWriter.open ("firstFile.cpp");
fileWriter << "#include <iostream>" << endl;
fileWriter << "int main() {" << endl;
fileWriter << "\tstd::cout << \"hello world\" << std::endl;" << endl;
fileWriter << "\treturn 0;" << endl;
fileWriter << "}" << endl;
fileWriter.close();
return 0;
}
当上述程序执行时,它会创建一个名为“firstFile.cpp”的文本文件,其中包含以下代码:
firstFile.cpp
#include <iostream>
int main() {
std::cout << "hello world" << std::endl;
return 0;
}
它在执行时会在屏幕上打印“hello world”。
所以,我想在 main.cpp 文件中添加几行代码,要求 GCC 编译刚刚创建的新 firstFile.cpp。
我在 Ubuntu 和 Windows 平台上都使用 GNU gcc。
是否有可能通过调用编译器获得任何错误代码?如果不是为什么。
【问题讨论】:
-
system函数可能会有所帮助。 -
首先用g++代替gcc。 gcc 用于编译 C 源代码。 g++ 用于 C++ 源代码。
-
@secretgenes man gcc:
gcc - GNU project C and C++ compiler -
@OrangeDog:技术上正确,但实际上无关紧要。 gcc 错过了正确编译 C++ 程序所需的许多默认选项(关于链接器、包含路径等)。如果您尝试使用 gcc 编译任何重要的 C++ 程序,您通常会遇到链接器错误或(在更“复杂”的目标上)细微的故障。
-
@OrangeDog :虽然您可以使用 gcc 编译器编译 C++ 源代码,但它存在对象链接问题。 g++ 链接对象时会自动链接到标准 C++ 库中,而 gcc 不是这种情况。