Skip to content

๐ŸŒซ Extern Keyword

Feldwor edited this page Nov 11, 2021 · 31 revisions

Type of keyword: for notice and error generation in c programs, declaration of external variables/functions requirement in the source code file.

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 keyword is simply a contract between other Relocatable Objects, stating that variable or function is to be found (declared) in any other compiled Relocatable Objects during the process of Relocatable Objects linkage.

Note: Relocatable object file is assembly version of the source code, produced from the source code file.

If the variable is not found as declared in the external source file,
linker produces an error saying that Symbol is not defined,

  • tcc: error:undefined symbol
  • gcc: `undefined reference to `var'`.   
    error: ld returned 1 exit status
    

This error means that the linker did not find external variable in other relocatable objects.
Declaring variable without definition, the default value is set to 0 of int variable, instead of random integer.

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/
https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1321396234&id=1043284376