views:

288

answers:

2

In Solaris, gcc gives me

implicit declaration of function `getopt'

when compiling

#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    getopt(1,argv,"");
    return 0;
}

The man page for getopt says something about including unistd.h or stdio.h, however even though I'm inluding both I still get this warning. Is this normal? Is using functions that aren't explicitly declared common in Unix development?

+1  A: 

The man page says to include stdio.h, not stdlib.h. Does including stdio.h fix the problem?

sth
No, I'll update the question to reflext that
Steven
+4  A: 

You're compiling with -ansi, and in that mode getopt might not be available, since -ansi implies C89 conformant mode. Try removing that switch, or #define _GNU_SOURCE before #include <unistd.h>. getopt() is POSIX, not ANSI.

Edit: You probably don't need _GNU_SOURCE. According to this, you should be able to get the functionality with defining preprocessor macros such that this is true:

#if _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE || _POSIX_SOURCE

See this for more information on the feature test macros.

Alok
removing -ansi does indeed remove the warning. However, I wonder why getopt() is not C89 conformant when every other POSIX function I've used didn't give any warnings#define _GNU_SOURCE doesn't though (this is Solaris)
Steven
See my edit. C89 doesn't define getopt: so it would be wrong for glibc to expose it when compiling in C89 mode. Although, since it's declared in unistd.h, which doesn't exist in C89, maybe glibc can do this, I am not sure.
Alok