【问题标题】:mingw: function not found when compiled with -std=c++11mingw:使用 -std=c++11 编译时找不到函数
【发布时间】:2014-04-05 16:10:36
【问题描述】:

我试图编译下面的代码(来自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() {}

【问题讨论】:

  • 与你的当前问题无关,但不要这样做while (!feof(...)),它不会像你期望的那样工作。原因是EOF 标志直到您尝试从文件末尾之外读取时才会设置,因此您将迭代一次到多次。相反,在您的情况下,只需执行while (fgets(...) != 0)。从 C++ 流中读取时也是如此。

标签: c++ c++11 mingw popen stdio


【解决方案1】:

我认为这是因为 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__ 当且仅当在调用 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)。

【讨论】:

    【解决方案2】:

    只需在开头添加:

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

    【讨论】:

    • 这适用于popen,但同样不适用于pclose。任何线索为什么?
    • @PeDro 你试过extern "C" FILE *pclose(const char *command, const char *mode);吗?
    • 老实说,我不知道 popen 和 pclose 是否属于同一个家庭
    • 我做了,它抛出了一些错误。但评论它对我有用。 :)
    • @PeDro。应该尝试过 - extern "C" void pclose(FILE *pipe);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    相关资源
    最近更新 更多