Subprocess in C++11 (mingw)

Here's how:

So this is just a reminder that you can always use extern! Create traditional c++ with function to run subprocess using _popen, and link that function to your c++11 source using extern


#include <string> #include <iostream> #include <fstream> #ifdef WINDOWS #define popen _popen #define pclose _pclose #endif std::string exec(char* cmd) { FILE* pipe = popen(cmd, "r"); if (!pipe) return "ERROR"; char buffer[128]; std::string result = ""; while (!feof(pipe)) { if(fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); return result; }


#include <string> #include <iostream> #include <fstream> extern std::string exec(char* cmd); int main() { std::string k(""); k = exec("ls"); std::cout<< k; }


C:\> g++ -DWINDOWS -c subprocess.cpp C:\> g++ -std=c++11 -c main.cpp C:\> g++ -std=c++11 main.o subprocess.o -o main.exe