John Lui
John Lui

Reputation: 1464

Can a static variable be declared extern in C?

So, let's say, I have:

file1.c

int i;
static int j;
int main ()
{
    for ( int k = 0; k < 10; k++ )
    {
       int foo = k;
    }
}

file2.c

{
// the following statements are before main.
extern int i; // this is acceptable, I know since i acts as a global variable in the other file
extern int j; // Will this be valid? 
extern int foo; // Will this be valid as well?
}

I therefore, have a doubt that the statements marked with a question mark, will they be valid?

Upvotes: 6

Views: 16400

Answers (2)

Balu
Balu

Reputation: 2447

extern int j; is not a valid -> static variables are with in the file scope

extern int foo; is not valid -> foo is a local variable whose scope is with in the 'for' loop

Upvotes: 0

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

No! static globals have file scope (internal linkage), so you can't use them as they have external linkage... This does not means that you cannot have a variable of the same name with external linkage but it cannot be that one that is static.

Correct for i.

Incorrect for j, at least it cannot be the one defined in file1.c.

Incorrect for foo, at least for the local variable used in file2.c which does not have external linkage (no linkage at all). A local variable only exists when the block where it is declared is activated, so having access to it outside is a non-sense.

Upvotes: 14

Related Questions