Alex Rivera | Logout

unistd.h and c99 on Linux

Asked 2010-07-28T16:51:26.303
14

This simple .c file:

#include <unistd.h>

void test() {
   char string[40];
   gethostname(string,40);
}

... when compiled normally, works fine:

$ cc  -Wall -c -o tmp.o tmp.c
$

... but when compiled in C99 mode, gives a warning:

$ cc -Wall -std=c99 -c -o tmp.o tmp.c 
tmp.c: In function `test':
tmp.c:5: warning: implicit declaration of function `gethostname'
$

The resultant .o file is fine, and linking works. I'd just like to get rid of the warning. I can achieve this in a hacky way, by putting declarations in my own .h file.

What is it about C99 that means the declarations in unistd.h don't get included? Can this be overcome, without giving up the niceness of C99?

I see the same problem for other standard libs.

Edit
Report

1 Answer

5

Read man gethostname. It says in the Feature Test Macro Requirements, that _BSD_SOURCE (or _XOPEN_SOURCE>500) is required to pull gethostname from unistd.h.

Next read man feature_test_macros. You will find that -std=c99 turns on __STRICT_ANSI__ which in turns off _BSD_SOURCE. This means you can't get gethostname from unistd.h unless you define _BSD_SOURCE again. I usually place _GNU_SOURCE on my command line (i.e. gcc -D_GNU_SOURCE -std=c99 file.c) for most things, which turns on _BSD_SOURCE as well.

P.S. The manual page contains an example program which can print the current ft-macros. You might compile and run it for some compiler settings.

answered 2010-07-28T17:29:05.110

Your Answer