Search code examples
cextern

Correct use of extern when using global variables imported from standard library?


I am trying to learn the use of the extern keyword. As an example I am using the getopt C library function. From my understanding of the extern keyword, it used to indicate to the compiler that a certain variable that has been defined in another file is going to be used. So whenever I am going to be using the getopt variables like opterr, optind, etc, should I(would it be wrong of me to) do this:

#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>

extern int optopt;
extern int opterr;
extern int optind;
extern char *optarg;

int main(int argc, char **argv)  {
   /* code using getopt */
}

When I looked at the manpage for getopt(3), I saw these declarations already mentioned under #include <unistd.h>. So I thought that these were declared in that header file but when I looked into the header file itself, there was no such declaration.

So my question is: is there anything wrong with using these statements at the beginning even if for the sake of improving readability for someone who doesn't how getopt works. Also, at the end of the day if the linker is going to resolve references, anyways, is there any reason to use extern at all?


Solution

    1. Header files can be nested.
      unitstd.h includes many other files, the specific declarations you are looking for are in getopt.h,

    2. These statements do not improve readability, they decrease it by adding duplicate garbage code.
      A programmer familiar with C but not with getopt function would think these are your custom variables, not part of the standard library, because nothing in the standard library should be redeclared.

    3. The linker is the last step in building the executable.
      The external keyword is for the compiler to know the names and types, so it can build code with references for the linker to resolve later.