Gcc and g++ different on write()

Viewed 19049
#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. But use g++ I got :

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?

4 Answers

This is because gcc is a C compiler, g++ is a C++ compiler, and C and C++ are different languages.

If you want to compiler that source code as C++ program, you must change it to become C++. For example, there are no implicit function declarations in C++, so you must include unistd.h for read() and write() declarations. You also don't need syscall.h header.

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.

P.S.: And instead of defining weird BUFSIZE yourself, consider using standard 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++ doesn't allow that, you need to include the correct header file, unistd.h, which you should also do in C.

Related