简体   繁体   English

写()上的Gcc和g ++不同

[英]Gcc and g++ different on write()

#include <sys/syscall.h>
#define BUFSIZE 1024

main()
{
     char buf[BUFSIZE];
     int n;
     while((n=read(0,buf,BUFSIZE))>0)
         write(1,buf,n);
     return 0;
}

When I compile this by using gcc, it is fine. 当我使用gcc编译它时,它很好。 But use g++ I got : 但是使用g ++我得到了:

inandout.c:7:32: error: ‘read’ was not declared in this scope
     while((n=read(0,buf,BUFSIZE))>0)
                                ^
inandout.c:8:22: error: ‘write’ was not declared in this scope
         write(1,buf,n);
                      ^

Why is that? 这是为什么?

This is because gcc is a C compiler, g++ is a C++ compiler, and C and C++ are different languages . 这是因为gcc是C编译器,g ++是C ++编译器, C和C ++是不同的语言

If you want to compiler that source code as C++ program, you must change it to become C++. 如果要将源代码编译为C ++程序,则必须将其更改为C ++。 For example, there are no implicit function declarations in C++, so you must include unistd.h for read() and write() declarations. 例如,C ++中没有隐式函数声明,因此必须为read()write()声明包含unistd.h You also don't need syscall.h header. 您也不需要syscall.h头文件。

Also, it is only that simple because you have a simple code snippet. 而且,它只是那么简单,因为你有一个简单的代码片段。 Porting C code to C++ could be a nightmare as there are ~ 50 differences and in some cases code compiles well in both cases, but behaves differently. 将C代码移植到C ++可能是一场噩梦,因为有大约50个差异,在某些情况下代码编译得很好,但行为不同。

PS: And instead of defining weird BUFSIZE yourself, consider using standard BUFSIZ :) PS:而不是自己定义奇怪的BUFSIZE,考虑使用标准BUFSIZ :)

C defaults functions that do not have a prototype to a function that returns an int - but you should have got warnings for that (did you use -Wall ?). C默认函数没有原型到返回int的函数 - 但你应该得到警告(你使用-Wall ?)。

C++ doesn't allow that, you need to include the correct header file, unistd.h , which you should also do in C. C ++不允许这样做,你需要包含正确的头文件unistd.h ,你也应该在C中做。

你只需要添加include <unistd.h>

I upgraded to gcc 4.8.5. 我升级到gcc 4.8.5。 In version 4.7 the compiler stopped including unistd.h in a number of include files. 在版本4.7中,编译器在许多包含文件中停止包含unistd.h。 This is why older gcc compiler versions worked without including unistd.h. 这就是为什么旧的gcc编译器版本工作而不包括unistd.h。

https://gcc.gnu.org/gcc-4.7/porting_to.html "C++ language issues Header dependency changes Many of the standard C++ library include files have been edited to no longer include unistd.h to remove namespace pollution. " https://gcc.gnu.org/gcc-4.7/porting_to.html“C ++语言问题标题依赖项更改许多标准C ++库包含文件已被编辑为不再包含unistd.h以消除名称空间污染。”

In my case I got ::write has not been declared when I included stdio.h, but my previous gcc version 4.4 compiled fine. 在我的情况下,当我包含stdio.h时,我得到:: write尚未声明,但我之前的gcc版本4.4编译得很好。 This is a useful command to see what paths are being searched by the preprocessor: g++ -H test.cpp 这是一个有用的命令,用于查看预处理器正在搜索的路径:g ++ -H test.cpp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM