views:

214

answers:

4

When I compile a program using just

gcc code.c

There are no messages, and an output file is generated successfully. The outputted file works. However, when I try to the same cygwin installation's gcc compiler in an IDE (I've tried Netbeans and Dev-C++), I get the following errors

main.cpp:27: error: `exit' undeclared (first use this function)
main.cpp:27: error: (Each undeclared identifier is reported only once for each function it appears in.)
main.cpp:77: error: `write' undeclared (first use this function)
main.cpp:78: error: `close' undeclared (first use this function)

I don't see what's different. Why does it not compile?

OK, the issue was that in the IDE, the file had a .cpp extension, whereas when I was compiling from a terminal, it had a .c extension. So, my new question is why does it not compile when it's treated as a c++ file. Isn't C a subset of C++?

A: 

You will have to use g++ for compiling .cpp files.

codaddict
exit(),write(),close() are all supported by C.
Neeraj
like I've said, it compiles fine when I do 'gcc file.c'
verhogen
A: 

One possible reason may be that the IDE is unable to access the include files, the cygwin gcc compiler may be expecting it in /usr/include(not sure), and the dev-cpp may not be able to access it.

Neeraj
+1  A: 

C++ is stricter then C. Where C allows you to call a function without a prototype, C++ does not allow this.

To solve the problem, you want to add:

#include <stdlib.h>

Also, when compiling at the command line. Make sure to use the -Wall flag so you'll get important warnings:

gcc -Wall code.c
R Samuel Klatchko
+1  A: 

The IDE is using fussier options to the compiler. You need to include some headers:

#include <stdlib.h>  // exit()
#include <unistd.h>  // close(), write()

The default options allow almost anything that might be C to compile. By the looks of it, the IDE sets '-Wmissing-prototypes' as one of the compiler options.


If you compile code with a C++ compiler, you must ensure that all functions are declared before use. C is sloppier (or can be sloppier) about that - it is recommended practice to ensure all functions are declared before being defined or referenced, but it is not mandatory. In C++ it is not optional.

There is a subset of C that is also a subset of C++; there are bits of C that are not C++, and there are many bits of C++ that are not C. In particular, an arbitrary C program is not, in general, a C++ program. For example, a C program may not declare 'exit()' and yet it can both use it and still compile. A C++ program must declare 'exit()' before it can user it and compile.

Jonathan Leffler