【问题标题】:Writing a script within the program to write and compile the code在程序中编写脚本来编写和编译代码
【发布时间】:2020-07-11 11:40:55
【问题描述】:

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

例如:

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

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

我想要这样的东西,我的计划是制作一种转换为 c++ 的基本脚本语言,然后 c++ 自行编译并执行。

【问题讨论】:

  • 这基本上是不可能的,除非你自己写一个C++编译器。或者你从你的程序中调用 c++ 编译器。
  • 在 Windows 中,有活动脚本可以执行,适用于 JavaScript 等解释性语言
  • 例如,如果您在 Linux 中,您可以在字符串中回显您的代码并将其通过管道传输到 gcc。看看这个问题:stackoverflow.com/questions/38299086/…
  • 当然你可以添加一个&amp;&amp; ./&lt;name-of-your-program-executable&gt;来执行它,如果构建成功的话。
  • 如果字符串本身就是有效的 c++ 代码,那么这就是您的编译器的用途。如何操作内容是一个操作系统问题,因此您确实应该提供相关信息。

标签: c++ compilation execute


【解决方案1】:

在不同的 shell 上执行不同的命令。例如,Unix 需要$ ./program,PowerShell 需要&gt; ./program(.exe 之类的),CMD 什么都不需要(只需&gt; 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2011-05-29
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2018-05-05
    相关资源
    最近更新 更多