mingw:使用 -std=c++11 编译时找不到函数

mingw: function not found when compiled with -std=c++11

本文关键字:编译 找不到 函数 c++11 使用 -std mingw      更新时间:2023-10-16

我试图编译下面的代码(从 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 和 WindowsXP64 的 mingw32 gcc4.8.1)

法典:

#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);