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

Viewed 8522

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.

6 Answers
Related