Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
upto me what i understood about extern keyword is , it will just used for declaration and wont allocate memory for that variable with exception that memory will be allocated when it initialized.
so,
1)
C++
#include<stdio.h>
extern int n=10;
void main()
{
    printf("%d",n);
}

output : 10


2)
now,
C++
#include<stdio.h>
void main()
{
extern int n=10;
printf("%d",n);
}

but when i give extern with in main i am getting error saying extern variable cannot be initialized. then why it does not shows error when i declare it outside. i googled but i didnot get clear idea.
can any one say me the reason ?
Posted
Updated 13-Jun-15 2:56am
v2
Comments
nv3 13-Jun-15 7:38am    
To define a global variable write the definition outside the scope of a function, give it an initial value, and DO NOT us extern. In all other places that want to use that same variable use extern and no initialization value.
moyna coder 13-Jun-15 8:30am    
but it confuses..am not yet clear
in 2nd program y am getting error .can you say
nv3 13-Jun-15 9:14am    
In the second program you are trying to declare a global variable inside a function and that is a contradiction. That is probably what the error message says you are getting.
moyna coder 13-Jun-15 10:19am    
but see if i have a file "ex.c"having an
initialitation of a =50 ..and
#include"ex.c"
void main()
{
extern int a;
printf("%d",a);
}
now it prints a without an error.
so which means extern can also be used as local know .
the error i got in 2nd program is initialization is not allowed in extern ..it does not say extern is not allowed here.

extern says that the variable is declared to be available in a different file, and that the actual location will not be known until the compiled files are linked together.
You can't use it inside a function declaration because it always refers to a global variable rather than a local one.

See here: http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/[^]
 
Share this answer
 
Comments
moyna coder 13-Jun-15 8:35am    
but see if i have a file "ex.c"having an initialitation of a =50 ..and
#include"ex.c"
void main()
{
extern int a;
printf("%d",a);
}
it prints a..so its not that extern should refer only global..we can also have it as local know..am asking d difference between the usage.
OriginalGriff 13-Jun-15 10:21am    
No, you are getting "local" confused.
"local" does not mean "in the same file" - it means "local to the current function" and is different to "global" which basically means "not inside a function".

And do yourself a big favour: Never #include .C source files, only .H Header files.
Let the linker join separate OBJ files (the output from the compiler) into an executable.
Otherwise you end up with a monolithic source file spread over many files and it takes a lot longer to build when you start running serious applications.
moyna coder 13-Jun-15 10:25am    
oh fine thankz.. ok then ..but extern can also be given outside main and also inside main.. am i right??
OriginalGriff 13-Jun-15 10:31am    
No. Main is a function.
moyna coder 13-Jun-15 10:37am    
#include"ex.c"
void main()
{
extern int a;
printf("%d",a);
}
yeah main is a function..see this shows no error..though i gave extern inside main()
To understand the reasons behind the compiler behavior that seems so strange to you, you have to learn better about variable scopes (can have a look here[^] and here[^]).
The variables in a C program have 3 main scopes: Global, Local or parameter.
The scope is in effect the location, strictly circumscribable, where a variable can exist and be used.
A global scope means that the variable can be accessed anywhere in your program, from inside and outside functions, and from any program module (file) that is included in your program.
But another very important property of the scope is that it allows the 'masking' of variables having same name, but different scope. Yes you can have more variables having the same name in the same piece of code, in the same file and even in the same function, but all of them must have different scopes, and of course each scope must be well identifiable or the compiler will throw errors.
Consider following code:
C++
int var = 10;    //Global scope

void foo(void)
{
    printf ("Inside foo. var=%d\n", var);    //Will access global variable
}

void bar(int var)
{
    printf ("Inside bar. var=%d\n", var);    //Will access parameter scope variable
}

int main(int argc, char *argv[])
{
    int var = 20;    //Local scope

    do
    {
        int var = 5;    //Block scope (local inner scope)
        printf ("Inside do-while. var=%d\n", var);    //Will access inner local scope
    } while(0);

    printf ("Inside main. var=%d\n", var);    //Will access local scope

    foo();    //Will access global scope

    bar(7);   //Will access parameter scope
}

Here we have 3 scopes: a global one in the very first line of the example, 2 local scopes (one in the function as very first function line, and one in the do-while block as inner local scope), and finally a parameter scope.
The compiler strategy is simply to use the most closer declaration.
Now if you run the example you will get:
Inside do-while. var=5
Inside main. var=20
Inside foo. var=10
Inside bar. var=7

As you can see the first output line shows the value in the do-while loop that is the closer declaration to the point where we access the variable.
On the second output line we have the value declared in the main function body, again the closer one.
On third output line we access the global value because there is no other declaration in the local block, and the closer scope is the global one.
On the last output line we have the parameter value that overrides the global one.

Now we go back the the global declaration: each variable declared outside a function scope is automatically created as global variable (unless you limit it to current module, file, using the static qualifier), and is available over the whole program in all modules.
Please note that local and parameter variables declarations are always visible from the code that will use it, unlike the global declarations that can be declared in a module and used in another where there is no trace of it.
But how can we tell to the compiler that a variable we want to use exist somewhere in the program? Each module will not know of such a variable until when we will link all modules together, because only at that time we have access to all symbols defined over the modules.
The C language have a qualifier, extern, that tells to the compiler that such a variable exists somewhere and it have not to complain, because the linker will solve all later... ;) The compiler when found this qualifier believe us and accept to compile the unit with no errors.

Now: you cannot declare global variables inside a function or all scoping will not be applicable , so:
C++
void main()
{
    extern int n=10;
    printf("%d",n);
}

It's an error!! Because the extern qualifier tells to the compiler that we want declare a global variable.
While in:
C++
#include<stdio.h>
extern int n=10;
void main()
{
    printf("%d",n);
}</stdio.h>

The qualifier extern is redundant!!

I hope this clearified your mind now :)

P.S. to be more clear, if you write:
C++
void main()
{
    extern int a;
    printf("%d",a);
}

In this case "extern int a;" is used to inform the compiler that exists a global variable , 'a', somewhere in the program. Just informs the compiler that the variable exist!
But if you write:
C++
void main()
{
    extern int a = 10;
    printf("%d",a);
}

You not only inform the compiler (declaring the variable), but you want also create and initialize the global variable inside a function. And, as I told before, this is an error!!!!
 
Share this answer
 
v7
Comments
moyna coder 13-Jun-15 10:29am    
yeah am getting what u are trying to say thankz for such a big explanation.
but see if i have a file "ex.c"having an
initialitation of a =50 ..and
#include"ex.c"
void main()
{
extern int a;
printf("%d",a);
}
now it prints a without an error.
so which means extern can also be used
inside main know .
the error i got in 2nd program is
initialization is not allowed in extern ..it
does not say extern is not allowed her
Frankie-C 13-Jun-15 10:53am    
I explained in the updated answer.
The fact that the compiler doesn't give you an error when you don't try to initialize the variable doesn't mean that *you are allowed to use extern in a function body*!
moyna coder 13-Jun-15 11:22am    
yeah We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally.

#include <stdio.h>
int main(){
extern int i=10; //Try to initialize extern variable
//locally.
printf("%d",i);
return 0;
}
Output: Compilation error: Cannot initialize extern variable.

If we declare any variable as extern variable then it searches that variable either it has been initialized or not. If it has been initialized which may be either extern or static* then it is ok otherwise compiler will show an error. For example:


#include <stdio.h>
int main(){
extern int i; //It will search the initialization of
//variable i.
printf("%d",i);
return 0;
}
int i=20; //Initialization of variable i.(this can also be extern int i=20 or static int i=20)

Output: 20
so extern can be declared inside main but it cant be initialized inside main thats the fact i got it.thank you..
have a try.
Frankie-C 13-Jun-15 13:16pm    
More or less.
You still consider only 2 actions toward a variable: declaration and initialization. But they are 3: declaration, initialization and instantiate.
When you declare a variable you tell to the compiler that exists a variable of that type with that properties, the initialization allows you to assign an initial value to the variable. The compiler can decide to instantiate a variable (effectively create it) depending on the declaration.
Declaring a variable as extern doesn't instruct the compiler to *create* the variable. It can only get some information without creating any instance of the variable.
But when you make a declaration having an initialization you are telling to the compiler to *create* the variable, but it cannot because the position is wrong. That is the reason of the error.
Now if the answer satisfy you accept it, else I really don't know how to explain better.
moyna coder 13-Jun-15 14:12pm    
yeah thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900