Seeker posted:
I have some code that #includes a file and declares a function with
extern whose declaration was also in the included file. Why is this?
Should we re-declare the functions with extern? Why don't we just use
the function? Why do we include it then?
Short answer: Take out the "extern" -- it isn't doing anything. (Unless
the functions is "inline", in which case, read... )
Long answer:
C has loads of abbreviations all over the place (well, I like to think of
them as abbreviations). Consider:
int main()
{
long i;
}
instead of:
signed int main(void)
{
signed long int auto i;
return 0;
}
Looking at the above snippet, a variable within a function defaults to
"auto" rather than "static", and a "long int" defaults to signed, rather
than unsigned.
There are some keywords in C that get omitted 99.9999992423211244% of the
time (like "auto" in the previous example).
When you define a variable within a function, it must be either "auto" or
"static", i.e.:
int main(void)
{
static int i = 5;
auto int j = 5;
}
If neither keyword is present, then it defaults to "auto".
Moving on to global variables...
Global variables, and also functions, must be either "extern" or
"static".
"extern" means that they CAN be accessed from other source files.
"static" means that they can NOT be accessed from other source files.
If neither keyword is present, then it defaults to "extern". (C++ is
different in this regard, just so you know...)
So... the question is, "What use is there for extern?". I'll tell you one
usage.
By writing:
extern int i;
instead of:
int i;
you're saying to the compiler, "I'm not defining an object, I'm just
forward-declaring one".
So if you want access to an object which is DEFINED within another source
file, then you DECLARE the object in the current source file by using the
keyword "extern".
(I suppose you could say that the functionality of "extern" is extended
to indicate that you want a declaration rather than a definition).
"extern" has no noticible effect whatsoever when placed before a function
(unless the function is inline... could someone please confirm that?).