sa*****@yahoo.c o.in writes:
I have seen in some project where functions are declared as extern,
what is the possible reason to do this? To my best understanding, if
some other file wan't to invoke this function, it could very well be
done ny including a header file which specifies the function
prototype...
As pete points out, function declarations are extern by default, but
that doesn't really answer the question.
I think you're asking why someone would have a declaration for an
external function (one defined elsewhere) in a source file, rather
than having a "#include" for the header file that declares it.
For example, a program that uses malloc() and free() might contain:
extern void *malloc(size_t) ;
extern void free(void*);
(the "extern" keywords aren't necessary but might be more explicit)
rather than the usual "#include <stdlib.h>".
Both are equivalent as far as the compiler is concerned, assuming the
header contains equivalent declarations. #include'ing a header
effectively copies the contents of that header into your source file.
Later phases of the compiler don't care whether a given function
declaration is from an included header or from the source file itself.
One disadvantage of re-declaring a function in another source file is
that it's too easy to get it wrong. If your declaration doesn't match
the actual declaration of the function, the compiler likely won't be
able to warn you about the error, and any calls will invoke undefined
behavior. You can avoid this by declaring the function in just one
place, in a header file to be #include'd by any source file that needs
it -- including the source file that actually defines the function.
In the case of the standard library functions, and user-defined
libraries as well, this also gives the header the opportunity to play
tricks like defining a macro to be invoked in place of the function.
There's no good reason I can think of to re-declare a function like
this. It's legal, and some programmers will do it that way, but IMHO
it's poor style.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.