我试图编译下面的代码(来自https://stackoverflow.com/a/478960/683218)。 如果我使用
进行编译,则编译顺利$ 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() {}
我认为发生这种情况是因为
popen
不是标准 ISO C++(它来自 POSIX.1-2001)。
您可以尝试:
$ g++ -std=c++11 -U__STRICT_ANSI__ test.cpp
(
-U
取消任何先前的宏定义,无论是内置的还是随-D
选项提供的)
或
$ g++ -std=gnu++11 test.cpp
(GCC 定义
__STRICT_ANSI__
当且仅当调用 GCC 时指定了 -ansi
开关或指定严格符合某些版本的 ISO C 或 ISO C++ 的 -std
开关)
使用
_POSIX_SOURCE
/ _POSIX_C_SOURCE
宏是一种可能的替代方案 (http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html)。
只需在开头添加此:
extern "C" FILE *popen(const char *command, const char *mode);
我知道这似乎是一个简单的解决方案,但只需添加此标题即可:
#include <stdio.h>
即使您使用
-std=c++98
进行编译,它也会起作用。