extern declaration and function definition both in the same file
Asked Answered
F

5

12

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?

Feathered answered 13/4, 2012 at 7:46 Comment(0)
B
16

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.

Bagworm answered 13/4, 2012 at 7:49 Comment(0)
F
7

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.

Fibro answered 13/4, 2012 at 7:48 Comment(2)
Yup. Use extern when doing something non-standard.Mezzorelievo
@Mezzorelievo What kind of non-standard things would this be applicable to?Conchoidal
G
3

In a function declaration, extern simply declares that the function has external linkage, which is the default; the extern keyword is utterly useless in this context, and the effect is identical to a normal declaration/prototype without the extern keyword.

Gerontocracy answered 13/4, 2012 at 7:49 Comment(0)
C
0

The warnings likely suggested a function prototype was missing. That's all.

Cento answered 13/4, 2012 at 7:48 Comment(0)
Z
0

The definition of the main function:

int main(int argc, char **argv) { ... }

is already a declaration is the prototyped syntax of the function main with external linkage. This means a prototyped declaration with extern just before the main definition is redundant.

Zecchino answered 13/4, 2012 at 7:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.