c++g++-4.7

Error "'fdopen' was not declared" found with g++ 4 that compiled with g++3


I have code that compiled happily with g++ version 3.something. I then wanted to build some other code that had C++11 symbols in it so I upgraded to g++ 4.7. Now my original code doesn't build. I get the error:

'fdopen' was not declared in this scope

According to the man page, fdopen() is declared in stdio.h which I am including. I'm not sure it is relevant, but I am working in a Cygwin environment. The exact version of g++ I am using is version 4.7.2 provided by Cygwin.

I have not changed this code since I switched compiler and I can definitely confirm that it built and my test code ran and passed with the previous compiler.

As requested, example code to demonstrate the problem:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
    int   fd;
    FILE *fp;

    fd = open("test.txt", (O_WRONLY | O_CREAT | O_EXCL), S_IRWXU);
    if(0 < fd)
    {
        fp = fdopen(fd, "wb");

        fprintf(fp, "Testing...\n");
        fclose(fp);
    }

    return 0;
}


# g++ -std=c++11 -o test test.cpp
test.cpp: In function 'int main(int, char**)':
test.cpp:14:29: error: 'fdopen' was not declared in this scope

Solution

  • The problem comes from -std=c++11. The fdopen() function is not in ANSI C (only in the POSIX standard), and compiling with -std=c++11 option implies defining __STRICT_ANSI__, which excludes several functions from stdio.h. By the way, in C++ programs, you should normally include <cstdio> instead of <stdio.h>, see here: stdio.h not standard in C++?.

    If you need to use fdopen(), you might want to remove the -std=c++11 option when compiling. Another possible soltion, although not really elegant, can be to use this in your source code:

    #ifdef __STRICT_ANSI__
    #undef __STRICT_ANSI__
    #include <cstdio>
    #define __STRICT_ANSI__
    #else
    #include <cstdio>
    #endif
    

    (which is intended to work with and without the -std=c++11 option).