Let only one global live! The extern keyword

To demonstrate the use of the extern keyword with global variables in C, I'll create a simple example involving two source files. The extern keyword is used to declare a global variable in one file, which is defined in another. This approach allows multiple files to access the same global variable.

File 1: main.c

#include <stdio.h>

extern int globalVar; // Declaration of the global variable

int main() {
    printf("Value of globalVar in main.c: %d\n", globalVar);
    return 0;

File 2: globals.c

int globalVar = 10; // Definition of the global variable

Compilation and Execution Commands

gcc -c globals.c   # Compiles globals.c into globals.o
gcc -c main.c      # Compiles main.c into main.o
gcc -o program main.o globals.o  # Links both object files into one executable
./program          # Executes the compiled program


  • globals.c: This file contains the definition of globalVar. This means that the actual storage for the variable is allocated here.

  • main.c: Here, extern int globalVar; is a declaration, not a definition. It tells the compiler that globalVar exists somewhere in the program, but its memory is allocated elsewhere (in this case, in globals.c). This file uses globalVar as if it were declared locally.

  • Compilation and Linking:

    • gcc -c is used to compile the .c files into object files (.o). This does not create an executable but prepares the code for linking.

    • gcc -o program links the two object files into a single executable named program. This step resolves the reference to globalVar in main.c by linking it to the definition in globals.o.

  • One Copy in Memory: Despite being accessed from two different files, there is only one copy of globalVar in memory. The extern keyword enables this single-instance access without duplicating the variable.

This approach is crucial in larger projects, where variables need to be shared across different files without duplicating their definitions, thereby maintaining consistency and reducing memory usage.