
Patrick B. answered 05/18/19
Math and computer tutor/teacher
it is a signal to the compiler that the global var is declared in another file somewhere else.
syntax:
extern type varname;
Here is an example:
suppose we have a pointer to a device handler, like a singleton
printer instance.
in file, printer.h we have
.....
TPrinter * The_Printer; // which is defined, declared, and instantiated via init function or constructor
.....
Now in another header file, summary_report.h, that requires
the use of the printer, we have :
extern TPrinter * The_Printer;
when the source code files and linked, the extern var declarations
in the reporting code are matched against the one in the
printer code.
---------------------------------------
If you go and look inside all of the header files *.h in the include directory,
you will find THOUSANDS of extern statements. I did a grep "extern" *.* in
the include directory and it listed thousands of them, just out of curiosity.
In stdio.h alone there are like 30+
This makes sense, there is only ONE input stream (stdin), there is only
ONE output stream (stdout) , and there is only ONE error log (stderr).
So how can these three I/O streams be shared through so many different
source code files? The answer is the extern keyword.
everytime you #include <stdio.h> , or any header for that matter, your
source code has access to those objects.
That is how to create an API (application programmer interface)
That's how it works