Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern declaration and function definition both in the same file

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?

like image 296
Pavan Manjunath Avatar asked Apr 13 '12 07:04

Pavan Manjunath


People also ask

Can extern be used inside a function?

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.

Is function definition and declaration same?

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.

Is a function definition also a declaration?

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)

How is declaration of a function or variable different from definition When is an extern declaration required?

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.


2 Answers

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.

like image 96
paxdiablo Avatar answered Oct 19 '22 02:10

paxdiablo


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.

like image 25
cnicutar Avatar answered Oct 19 '22 03:10

cnicutar