Skip to content

๐ŸŒซ Extern Keyword

Feldwor edited this page Nov 6, 2021 · 31 revisions

Extern keyword is used to declare a variable that is outside the file and is defined in another file.
Extern keyword simply tells the linker that a variable or function is declared and defined outside this relocatable object.

extern tells the compiler that this data is defined somewhere and will be connected with the linker from other produced relocatable object after compilation, during objects linkage (before making executable object file).

file.c (Source code of the First .o Object File)

#include <stdio.h>
#include "somefile.h" // Declared external object with defined variable.
extern int var;  // Declare requirement of external variable
int main(void)
{
 var = 10; //redefined external variable into local variable
 printf("%i", var);
 return 0;
}

somefile.h (Source code of the Second .o Object File)

// int var; // External variable is always initialized to 0
int var = 15; // The external variable 

Compile and results

gcc file.c tcc -run file.c

10

Footnotes

https://stackoverflow.com/questions/496448/how-to-correctly-use-the-extern-keyword-in-c/499330#499330 https://www.geeksforgeeks.org/understanding-extern-keyword-in-c/