6

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?

John Lui
  • 1,434
  • 3
  • 23
  • 37

2 Answers2

14

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.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

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

Balu
  • 2,247
  • 1
  • 18
  • 23