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??

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.

@sepp2k thank you sir for your reply..can you please explain what do you mean by forward declare??

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.

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??

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.

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

@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;
}

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).

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.

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??
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.