Skip to content
Advertisement

Run Another Program in Linux from a C++ Program

Okay so my question is this. Say I have a simple C++ code:

#include <iostream>
using namespace std;

int main(){
   cout << "Hello World" << endl;
   return 0;
}

Now say I have this program that I would like to run in my program, call it prog. Running this in the terminal could be done by:

./prog

Is there a way to just do this from my simple C++ program? For instance

#include <iostream>
using namespace std;

int main(){
   ./prog ??
   cout << "Hello World" << endl;
   return 0;
}

Any feedback would be very much obliged.

Advertisement

Answer

You want the system() library call; see system(3). For example:

#include <cstdlib>

int main() {
   std::system("./prog");
   return 0;
}

The exact command string will be system-dependent, of course.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement