I was just browsing through gcc
source files. In gcc.c
, I found something like
extern int main (int, char **);
int
main (int argc, char **argv)
{
Now my doubt is extern
is to tell the compiler that the particular function is not in this file but will be found somewhere else in the project. But here, definition of main
is immediately after the extern
declaration. What purpose is the extern
declaration serving then?
It seems like, in this specific example, extern
seems to be behaving like export
that we use in assembly, wherin we export a particular symbol outside of the module
Any ideas?
The extern keyword in C and C++ extends the visibility of variables and functions across multiple source files. In the case of functions, the extern keyword is used implicitly. But with variables, you have to use the keyword explicitly.
The main difference between Function Declaration and Function Definition in C Programming is that Function declaration indicates what the function is and Function Definition indicates what the function does.
A function consist of two parts: Declaration: the function's name, return type, and parameters (if any) Definition: the body of the function (code to be executed)
Declaration can be done any number of times but definition only once. “extern” keyword is used to extend the visibility of variables/functions(). Since functions are visible through out the program by default. The use of extern is not needed in function declaration/definition.
You are misunderstanding the extern
- it does not tell the compiler the definition is in another file, it simply declares that it exists without defining it. It's perfectly okay for it to be defined in the same file.
C has the concept of declaration (declaring that something exists without defining it) and definition (actually bringing it into existence). You can declare something as often as you want but can only define it once.
Because functions have external linkage by default, the extern
keyword is irrelevant in this case.
Functions are implicitly extern in C. Including extern
is just a visual reminder. Side note, to make a function not extern you can use the static
keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With