Pages

Search This Blog

August 29, 2014

extern in C

Clear description can be found in this geeksforgeeks link. This post is a terse version of the article there.

In short, it has to do with declaration and definition of variables and functions in C.
Variables and functions can be declared (establishes type/signature) any number of times but are to be defined only once(provides actual space for variable and code for function in memory).

extern extends the visibility of the variables/functions. This makes variable/function in one module available for use throughout the program.

Functions:

. All the declarations in C are implicitly prepended with extern. So, any function declared anywhere in the program can be used anywhere else.
. There should be one and only one definition for a function and this will be referred during linking step to generate the code for the function.

Variables:

. When extern is used with a variable, it only declares the variable and so no memory is set aside for the variable. So a variable with extern declaration can't be used till it is initialized.
. C doesn't provide extern by default because commonly a variable is declared&defined with a construct 'Type object;' eg: int x; (Here, space to store int is set aside for x). If extern gets added here by default, obj will never be usable till it is initialized in some form.
. However, according to C standard, a declaration and definition can be combined. So, if there is a construct 'extern Type obj = initial_value;', memory is immediately set aside for the variable as the compiler perceives this as a declaration and definition step.

[Any comments to make this post more readable are welcome]

No comments:

Post a Comment