Question

{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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top