0

The following code gave error on gcc compiler

int main()
{
extern int a;
printf("%d",a);
return 0;
}
static int a=5;

But when static is removed from int a then it runs with no errors..Can someone please clear the doubt??

3
Contributors
10
Replies
34
Views
4 Years
Discussion Span
Last Post by saurabh.mehta.33234
0

If you're declaring a variable with extern, it must have external linkage. This means it can't be static. It is not possible to forward-declare a static variable. So your only option are to not make it static or to put the definition at the top of the file and get rid of the forward-declaration.

0

I meant what you're trying to do in your code: Define the variable at the end of the file, but declare it before then. You can't do that with a static variable.

0

When I ran the first code with static variable then it gave error as non static declaration of 'a' follows static declaration..Now can you please explain what this error means??

0

I thought I did: It means that if you're declaring a variable with extern, it must have external linkage and thus can't be static.

0

@sepp2k Then why does the code give no error if I remove static and write simply int a; a=5;

Edited by saurabh.mehta.33234

0

@sepp2k Then why does the code give no error if I remove static and write simply int a; a=5;

Because the default linkage at file scope is extern. This:

int a;

int main(void)
{
    a = 5;
    return 0;
}

Is functionally identical to this:

extern int a;

int main(void)
{
    a = 5;
    return 0;
}
1

No, these are not equivalent at all. If you try to compile and link the second piece of code, you'll get a linker error telling you that a has not been defined.

It is true that the default linkage is external, but extern does more than just saying that a variable's linkage is external. It also says that this is only a declaration - not a definition - and the corresponding definition can be found elsewhere (generally in a different compilation unit).

0

No, these are not equivalent at all. If you try to compile and link the second piece of code, you'll get a linker error telling you that a has not been defined.

My bad for being in a hurry. I forgot to include a definition to make the code compile. But the point remains: extern is the default when you don't explicitly state the linkage at file scope.

Edited by deceptikon

0

You can't do that with a static variable.

So can you do that with other variables like in case of extern or auto or register variables??

Edited by saurabh.mehta.33234

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.