8

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?

4
  • 2
    This can help you stackoverflow.com/questions/2841762/… Commented Jul 6, 2015 at 11:23
  • What prevented you from asking your compiler? Commented Jul 6, 2015 at 11:52
  • The question doesn't make any sense, extern and static are each other's opposites. You are essentially asking "can a red car be blue while it stays red?". Commented Jul 6, 2015 at 11:52
  • @molbdnilo compilers are not authoritative Commented Jul 6, 2015 at 11:59

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.