extern Keyword in C

Last Updated : 12 Jun, 2026

The extern keyword in C is used to declare variables and functions whose definitions are located in another source file.

  • Does not allocate memory for a variable or create a function definition.
  • Helps the linker resolve references across multiple source files.
  • Commonly used in multi-file programs to access shared global variables and functions.

Before learning about extern, it is useful to understand the following terms:

  • Declaration: Tells the compiler that a variable or function exists and specifies its type.
  • Definition: Creates the variable or function and allocates memory for it (in the case of variables).

Syntax

The usage syntax of extern is a multistep process. In the file, where we want to use the variable/function, we have to provide extern declaration:

Variable Declaration:

extern data_type variable_name;

Function Declaration:

extern return_type function_name(parameter_list);

Since functions have external linkage by default, the extern keyword is optional for function declarations.

Note: Only globally defined variables and functions can be accessed using extern. Local variables and objects with internal linkage (such as static variables) cannot be referenced using extern.

Examples of extern

The following examples demonstrate the use of extern keyword in C:

Access Global Variables Across Multiple Files

First create a file that contains the definition of a variable. It must be global variable,

src.c

C
// Definition of a variable
int ext_var = 22;

Create an extern declaration of this variable in the file where we want to use it.

main.c

C
#include <stdio.h>

// Extern decalration that will prompt compiler to
// search for the variable ext_var in other files
extern int ext_var;

void printExt() {
  	printf("%d", ext_var);
}
int main() {
    printExt();
    return 0;
}

Then we compile them together. For GCC, use the following command:

gcc main.c src.c -o main

Output

22

Access Functions Across Multiple Files

First define the function inside the src.c file.

src.c

C
#include <stdio.h>

void func() {
    printf("Hello");
}

Functions are extern by default, so we have a choice to use extern keyword here:

main.c

C
void func();

int main() {
    func();
    return 0;
}

Compile both of the files together and the output will be as shown.

Output

Hello

Applications of extern in C

Following are the primary applications of extern in C:

  • Sharing global variables across multiple files
  • extern plays a key role in linking with external libraries by declaring the functions and variables they provide in the header files.
  • extern promotes modularity by allowing different parts of a program to interact with each other.
  • By facilitating the sharing of variables and functions across files, extern enables code reuse.
Comment