如何以编程方式要求编译器在C++中编译文件

How to ask, programmatically, a compiler to compile a file in C++?

本文关键字:C++ 编译 文件 编译器 编程 方式      更新时间:2023-10-16

以下是我的C++程序:

主.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"的文本文件,其中包含以下代码:

第一个文件.cpp

#include <iostream>
int main() {
    std::cout << "hello world" << std::endl;
    return 0;
}

执行时,会在屏幕上打印"Hello World"。

因此,我想在主文件中添加.cpp代码行,要求GCC编译刚刚创建的新firstFile.cpp

我在 Ubuntu 和 Windows 平台上使用 GNU gcc。

是否可以从对编译器的调用中获取任何错误代码?如果不是为什么。

使用 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
}

输出:

Hello World!
gcc是一个

可执行文件,所以你必须使用system("gcc myfile.cpp")popen("gcc myfile.cpp"),这给你一个文件流作为结果。

但是,由于您无论如何都要生成代码,因此您甚至不需要将其写入文件。您可以使用 FILE* f = popen("gcc -x c++ <whatever flags> -") 打开 gcc 进程。然后你可以用fwrite(f, "<c++ code>")编写代码。我知道这很c,不是很c++但它可能有用。(我认为没有popen()c++版本)。

您需要做的就是在创建文件后添加以下行。

system("g++ firstFile.cpp -o hello");

适用于OS X,所以我希望它也能为您服务。

要在源文件中使用编译器的命令行,请使用系统函数。

语法为:

int system (const char* command); //built in function of g++ compiler.

在您的情况下,它应该像

system("g++ firstFile.cpp");

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;
}

根据你实际想要实现的目标,你也可以考虑在你的应用程序中嵌入一些C++编译器。

请注意,到目前为止,这并不像调用外部可执行文件那么容易,并且可能受到许可证限制(GPL)的约束。

另请注意,通过使用std::system或类似机制,您可以在目标环境中添加要求,以实际使调用的编译器可用(除非您以某种方式将其与应用程序捆绑在一起)。

像这样:

#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();
    system("c firstFile.cpp");
    return 0;
}

或任何适合您正在使用的编译器的命令。