Mingw: function not found when compiling with -std = C ++ 11

I was trying to compile the code below (from https://stackoverflow.com/a/21829/ ... ) The compilation went fine if I compile

$ g++ test.cpp 

but mistakenly when the -std=c++11 switch is used:

 $ g++ -std=c++11 test.cpp test.cpp: In function 'std::string exec(char*)': test.cpp:6:32: error: 'popen' was not declared in this scope FILE* pipe = popen(cmd, "r"); ^ 

Any idea what is going on?

(I am using mingw32 gcc4.8.1 from mingw.org and on WindowsXP64)

Code:

 #include <string> #include <iostream> #include <stdio.h> 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; } int main() {} 
+6
source share
2 answers

I think this is happening because popen not a C ++ ISO standard (it comes from POSIX.1-2001).

You can try:

 $ g++ -std=c++11 -U__STRICT_ANSI__ test.cpp 

( -U overrides any previous macro definition, either inline or with the -D option)

or

 $ g++ -std=gnu++11 test.cpp 

(GCC defines __STRICT_ANSI__ if and only if the -ansi switch or the -std switch, which defines strict compliance with some version of ISO C or ISO C ++, was specified when calling GCC)

Playing with macros _POSIX_SOURCE / _POSIX_C_SOURCE is a possible alternative ( http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html ).

+5
source

Just add this at the beginning:

 extern "C" FILE *popen(const char *command, const char *mode); 
0
source

All Articles