1

If we declare a variable in the beginning before main function without giving EXTERN keyword, will it be taken as a static global variable(can be accessed only in that file) or can we able to access it from other files? For example:

#include<stdio.h>
int k;
main()
{

}
user1762571
  • 1,888
  • 7
  • 28
  • 47

3 Answers3

4

The variable k will technically be available to other files (modules) but unless the other files have an extern int k declaration, they won't know about the variable and a compile time error will indicate that k is unknown in the other file.

lurker
  • 56,987
  • 9
  • 69
  • 103
  • So deoes it work as a static global variable? – user1762571 Jun 19 '13 at 22:37
  • 1
    And the usual way to make it visible is to declare `extern int k;` in a header file to be `#include`d by any any `*.c` file that needs to see it. (Which you normally wouldn't do for something defined in the same source file as `main()`.) – Keith Thompson Jun 19 '13 at 22:37
  • It's "static" in the sense that it has static storage duration; it exists for the entire execution of the program. It has external linkage, which means it's visible to other translation units (source files) has long as they have an `extern` declaration; defining it with the `static` keyword would disable that. The C standard doesn't use the term "global variable", so it's hard to say whether it's a "static global variable". – Keith Thompson Jun 19 '13 at 22:39
  • 1
    @user1762571, it isn't treated as `static` in the strict sense. It's treated as globally accessible by the compiler and the linker. It could be accessed by other files if they have the `extern`. If it were `static`, then even having an `extern` in the other file would not make it accessible to that other file. – lurker Jun 19 '13 at 22:39
1

external definition and declaration, default initialization to zero.

int k;

external declaration only, defined and initialized some where else

extern int k;

external definition, initialization and declaration

int k = 2;
sukumarst
  • 265
  • 1
  • 5
0
static int k;

It tells the compiler the variable k is accessable at file scocpe, can not be reached outside.

extern int k;

It tells the linker the variable k is linked to variable k in the other file.

int k;

It is the global scope, can not declare twice in two files.

Mr. C
  • 548
  • 5
  • 17