Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a static variable be declared extern in C?

Tags:

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?

like image 710
John Lui Avatar asked Jul 06 '15 11:07

John Lui


People also ask

Can static variables be declared outside the class?

Difference between static variables and global variablesStatic variables can be declared both inside and outside the main function while the global variables are always declared outside the main function.

Can we declare static variable in C?

Static is a keyword used in C programming language. It can be used with both variables and functions, i.e., we can declare a static variable and static function as well. An ordinary variable is limited to the scope in which it is defined, while the scope of the static variable is throughout the program.

Can we declare static variable as global?

A static variable can be either a global or local variable. Both are created by preceding the variable declaration with the keyword static. A local static variable is a variable that can maintain its value from one function call to another and it will exist until the program ends.

What is the use of extern static?

static means a variable will be globally known only in this file. extern means a global variable defined in another file will also be known in this file, and is also used for accessing functions defined in other files. A local variable defined in a function can also be declared as static .


1 Answers

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.

like image 160
Jean-Baptiste Yunès Avatar answered Sep 22 '22 23:09

Jean-Baptiste Yunès