How can I compile a cpp file from inside another cpp program?

Say, I have 2 files:
mainprogram.cpp
secondaryprogram.cpp
I compile the mainprogram.cpp normally.
Then, when i execute mainprogram.exe, I want it to compile the other file, secondaryprogram.cpp as if from the command line.

I can compile with g++ -o mainprogram E:\mainprogram.cpp
So naturally I tried this:
1
2
3
4
5
6
7
8
9
10
11
12
13
//mainprogram.cpp
#include <iostream>
#include <windows.h>

using namespace std;

int main()
{
    system("C:");
    system("cd c:\\mingw");
    system("g++ -o secondaryprogram E:\\secondaryprogram.cpp");
    return 0;
}

But this does not seem to work. I get no errors or anything, it just doesn't create the .exe file.

How can I do it?

Edit: I want to peocedurally generate multiple c++ files and compile them
Last edited on
If your target is Windows, you could try out the "ExecuteShell" function to call your compiler. but why you need to compile another program? if your "mainprogram"'s only purpose is handling your project, you should use a .bat script (or a .sh on Linux) instead.
There are several ways of doing that, but I don't recommend it as it influence with high complexity within the code. High complexity might lead your code to suffer from bugs and errors that are hard to be detected later. There programs that might help doing it, like checkmarx but it's recommended to try and avoid this kind of situations.
Good luck.
@Benhart So what would be a better alternative?
@barnack could you please exemplify how I would do that? I would make a bat script and call it using a ExecuteShell or system from withibg an actual c++ program ^^? I want this to be done from a c++ program.
Ps I updated the question
Last edited on
Use CreateProcess() to call your compiler.
https://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx
Topic archived. No new replies allowed.