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

This is not too difficult using the std::system command. Also raw string literals allow us to insert multiline text which is useful for typing in program parts:

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

Output:

Hello World!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)