Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was trying to compile the code below (from https://stackoverflow.com/a/478960/683218). The compile went OK, if I compile with

$ g++ test.cpp

but went wrong when the -std=c++11 switch is used:

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

Any idea what's going on?

(I am using mingw32 gcc4.8.1 from mingw.org, and on WindowsXP64)

Code:

#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() {}
like image 621
thor Avatar asked Mar 04 '14 08:03

thor


People also ask

How do I add MinGW to PATH in Windows 11?

In the Windows search bar, type 'settings' to open your Windows Settings. Search for Edit environment variables for your account. Choose the Path variable in your User variables and then select Edit. Select New and add the Mingw-w64 destination folder path to the system path.

How do I change my MinGW from 32-bit to 64-bit?

open a cmd.exe and do set PATH=C:\mingw64\bin;%PATH% for 64-bit building. set PATH=C:\mingw32\bin;%PATH% for 32-bit building. You should be ready to go.

Is MinGW 32 or 64-bit?

MinGW can be run either on the native Microsoft Windows platform, cross-hosted on Linux (or other Unix), or "cross-native" on Cygwin. Although programs produced under MinGW are 32-bit executables, they can be used both in 32 and 64-bit versions of Windows.


1 Answers

I think this happens because popen is not standard ISO C++ (it comes from POSIX.1-2001).

You could try with:

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

(-U cancels any previous definition of a macro, either built in or provided with a -D option)

or

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

(GCC defines __STRICT_ANSI__ if and only if the -ansi switch, or a -std switch specifying strict conformance to some version of ISO C or ISO C++, was specified when GCC was invoked)

Playing with the _POSIX_SOURCE / _POSIX_C_SOURCE macros is a possible alternative (http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html).

like image 186
manlio Avatar answered Sep 30 '22 07:09

manlio