错误“未声明'fdopen'”。在使用g ++ 3编译的g ++ 4中找到 [英] Error "'fdopen' was not declared" found with g++ 4 that compiled with g++3

查看:116
本文介绍了错误“未声明'fdopen'”。在使用g ++ 3编译的g ++ 4中找到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用g ++版本3.something进行愉快编译的代码。然后,我想构建一些其他具有C ++ 11符号的代码,因此我升级到了g ++ 4.7。现在,我的原始代码无法构建。我收到错误消息:

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'未在此范围内声明

'fdopen' was not declared in this scope

根据手册页,我在stdio.h中声明了fdopen()。我不确定是否相关,但是我正在Cygwin环境中工作。我使用的g ++的确切版本是Cygwin提供的4.7.2版本。

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


推荐答案

问题来自 -std = c ++ 11 fdopen()函数不在ANSI C中(仅在POSIX标准中),并且使用 -std = c ++ 11 选项意味着定义 __ STRICT_ANSI __ ,这从 stdio.h 中排除了几个功能。顺便说一句,在C ++程序中,通常应包括< cstdio> 而不是< stdio.h> ,请参见此处: stdio.h在C ++中不是标准的吗?

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++?.

如果需要使用 fdopen(),则可能要删除 -std = c ++ 11 选项。另一个可能的解决方法(虽然不是很优雅)可以在源代码中使用:

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

(用于和 -std = c ++ 11 选项)。

这篇关于错误“未声明'fdopen'”。在使用g ++ 3编译的g ++ 4中找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆