views:

225

answers:

1
{net04:~/xxxx/wip} gcc -o  write_test write_test.c
In file included from write_test.c:4:
global.h:10: warning: `b' initialized and declared `extern'

This code uses fcntl.h and the file-handling functions defined - like open(), write(), close() etc.. The code compiles and works as intended.

{net04:~/xxxx/wip} gcc -o  write_test write_test.cpp
In file included from write_test.cpp:4:
global.h:10: warning: `b' initialized and declared `extern'
write_test.cpp: In function `int main()':
write_test.cpp:56: error: `exit' undeclared (first use this function)
write_test.cpp:56: error: (Each undeclared identifier is reported only once for each function it appears in.)
write_test.cpp:58: error: `write' undeclared (first use this function)
write_test.cpp:62: error: `close' undeclared (first use this function)

When I use it as a CPP source code, why does GCC complain? And curiously, why it doesn't complain for open()? What's even happening here?

+5  A: 
  1. C++ is more strict about headers - you need: #include <unistd.h> to properly get the functions indicated.

  2. global.h should not be defining b - headers shouldn't initialise variables.

  3. When compiling you should use -Wall -Werror and that will force you to fix all the dodgy bits of your code.

  4. To get exit() cleanly you'll need #include <cstdlib> (C++) or #include <stdlib.h> (C)

  5. Use g++ to link C++ code so that C++ libraries get included. Probably easiest to do the entire C++ compile with g++.

Douglas Leeder
I've corrected my code according to your suggestions and now it does compile fine. But while trying to link it, I'm observing the following errors :{net04:~/xxxx/wip} gcc -o write_test write_test.cppUndefined first referenced symbol in file__gxx_personality_v0 /usr/tmp/cclwLzgI.old: fatal: Symbol referencing errors. No output written to write_testcollect2: ld returned 1 exit statusWhy's this happening?
halluc1nati0n
Use g++ to link C++ programs; use gcc to link C programs. If you mix C and C++, use g++.
Jonathan Leffler
Also, exit() is declared in `<cstdlib>` (C++) or `<stdlib.h>` (C).
Jonathan Leffler
@Jonathan Leffler Yes, I got that. I 'included'that and compiled it, but had linker issues.
halluc1nati0n
@Jonathan Leffler :Used g++ and all is fine now, kind of weird why gcc would crib whilst linking.
halluc1nati0n
I'm sure it *possible* to tell gcc to include all the C++ libraries, but given that g++ is designed precisely to compile C++ (and include appropriate libraries), it seems obtuse to try and use gcc.
Douglas Leeder