提问者:小点点

在程序中编写脚本来编写和编译代码


我希望能够用C++代码传入一个字符串,编译,然后用C++代码执行代码。

例如:

string code = "#include.... int main() {" \
              "std::cout << \"hello, world\" << std::endline;\n";

obj = compile(code);
execute(obj);

我想要这样的东西,我的计划是做一个基本的脚本语言,转换成C++,然后C++自己编译并执行。


共1个答案

匿名用户

在不同的shell上有不同的命令要执行。 例如,Unix需要$./program,PowerShell需要>; 。/program(与。exe类似),CMD不需要任何东西(只需要>program)。

#include <iostream>
#include <fstream>

int main(int argc, char **argv) {
    std::string c = argv[1];
    std::string fileName = c + ".cpp";

    std::ofstream write(fileName.c_str());
    std::string compile = "";

    const char *program =
        "#include <iostream>\n" \
        "int main(void) {\n" \
        "    std::cout << \"Hello World!\";\n" \
        "    return 0;\n" \
        "}";

    // designed for Windows Command Prompt
    compile = "g++ -o " + c + ' ' + fileName + " && " + c;

    write << program << std::endl;
    write.close();

    system(compile.c_str());
    
    return 0;
}