2014-03-04 132 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); 
相關問題