C Language | Structure Declarations | External Declarations - extern

The extern storage-class specifier declares a variable that is defined elsewhere. File-level static limits visibility to the current source file.

Referring to Global Variables

A declaration outside a function has file scope. It is visible after its declaration within that source file. Use extern when the definition appears elsewhere.

extern type variable_name;

An extern declaration does not allocate storage or initialize the variable.

#include <stdio.h>

extern char *str;

int main(void) {
  printf("%s\n", str);
  return 0;
}

char *str = "Kitty on your lap";

extern may also appear inside a block. In that case, the name is visible only in that block.

Static Global Variables

Without static, another source file can declare the same global variable with extern. Add static when a global variable should remain private to its source file.

#include <stdio.h>

static int iValue = 0xFF;

int main(void) {
  printf("iValue = %d\n", iValue);
  return 0;
}

Keeping implementation details private avoids accidental identifier conflicts and unintended access from other files.