以下是我的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;
}
Run Code Online (Sandbox Code Playgroud)
执行上述程序时,它会创建一个名为"firstFile.cpp"的文本文件,其中包含以下代码:
firstFile.cpp
#include <iostream>
int main() {
std::cout << "hello world" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
执行时,在屏幕上打印"hello world".
所以,我想在main.cpp文件中添加一行代码,要求GCC编译刚刚创建的新的firstFile.cpp.
我在平台Ubuntu和Windows上使用GNU gcc.
是否有可能从编译器调用中获取任何错误代码?如果没有原因.
Gal*_*lik 61
使用std :: system命令并不太难.另外原始字符串字面量使我们能够插入多行文本是在程序部分输入有用:
#include <cstdlib>
#include <fstream>
// Use raw string literal for easy coding
auto prog = R"~(
#include <iostream>
int main()
{
std::cout << "Hello World!" << '\n';
}
)~"; // raw string literal stops here
int main()
{
// save program to disk
std::ofstream("prog.cpp") << prog;
std::system("g++ -o prog prog.cpp"); // compile
std::system("./prog"); // run
}
Run Code Online (Sandbox Code Playgroud)
输出:
Hello World!
Run Code Online (Sandbox Code Playgroud)
Dav*_*ijn 14
gcc是一个可执行文件,所以你必须使用system("gcc myfile.cpp")或者popen("gcc myfile.cpp"),它会为你提供一个文件流.
但是,由于您无论如何都在生成代码,因此您甚至不需要将其写入文件.您可以使用打开gcc进程FILE* f = popen("gcc -x ++ <whatever flags>").然后你就可以编写你的代码了fwrite(f, "<c++ code>").我知道这c不是真的,c++但可能有用.(我认为没有c++版本popen()).
小智 13
您需要做的就是在创建文件后添加以下行.
system("g++ firstFile.cpp -o hello");
Run Code Online (Sandbox Code Playgroud)
适用于OS X,所以我希望它也适合你.
要在源文件中使用编译器的命令行,请使用系统函数.
语法是:
int system (const char* command); //built in function of g++ compiler.
Run Code Online (Sandbox Code Playgroud)
在你的情况下,它应该是
system("g++ firstFile.cpp");
Run Code Online (Sandbox Code Playgroud)
PS:系统函数不会抛出异常.
程序
#include <iostream>
#include <fstream>
#include <cstdlib>
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();
system("g++ firstFile.cpp");
return 0;
}
Run Code Online (Sandbox Code Playgroud)