2014-03-04 97 views
6

我试图编译下面的代码(从https://stackoverflow.com/a/478960/683218)。 的编译就OK,如果我mingw:使用-std = C++编译时找不到函数11

$ g++ test.cpp 

编译但是当-std=c++11开关使用了错误:

$ 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"); 
           ^

任何想法是怎么回事?

(我用从mingw.org mingw32的gcc4.8.1,并WindowsXP64)

代码:

#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() {} 
+4

完全无关的*电流*的问题,但不这样做''时,它不会像您期望的工作(FEOF(...)!)它来。原因是因为在你试图从文件末尾读取之后,EOF标志将不会被设置,直到*之后,所以你将迭代一次到多次。相反,在你的情况下,只需'while(fgets(...)!= 0)'。从C++流中读取时也是如此。 –

回答

5

我想这是因为popen不标准ISO C++(它来自POSIX .1-2001)。

你可以尝试用:

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

-U取消宏的任何以前的定义,无论是内置或具有-D选项)

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

(GCC defines__STRICT_ANSI__当且仅当-ansi开关或-std s巫指定严格符合一些版本ISO C或ISO C++的被调用时GCC

_POSIX_SOURCE/_POSIX_C_SOURCE宏播放,指定)是一种可能的选择(http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html)。

+0

谢谢。那样做了。 – tinlyx

0

就在开始时补充一点:

extern "C" FILE *popen(const char *command, const char *mode); 
相关问题