Ninda Ninda - 1 month ago 9
C++ Question

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

The following is my C++ program:

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


When the above program is executed, it creates a text-file named "firstFile.cpp" containing the following code:

firstFile.cpp

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


which, when executed, prints "hello world" on the screen.

So, I would like to add to the main.cpp file lines of code asking GCC to compile the new firstFile.cpp just created.

I am using GNU gcc on both platform Ubuntu and Windows.

Is it possible to get any error code form the call to the compiler? If not why.

Answer

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!