-
Notifications
You must be signed in to change notification settings - Fork 0
๐ซ Extern Keyword
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).
#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;
}
// int var; // External variable is always initialized to 0
int var = 15; // The external variable
gcc file.c
tcc -run file.c
10
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
TutorialsPoint Reference for C standard library is always useful.
https://www.tutorialspoint.com/c_standard_library/index.htm
General C language overview can be found on Geeks for Geeks.
https://www.geeksforgeeks.org/c-programming-language/
Advanced In-depth book on C language.
Extreme C: Taking you to the limit in Concurrency, OOP, and the most advanced capabilities of C
Quick simplistic tutorials on C language can be found here.
https://www.tutorialspoint.com/cprogramming/index.htm
https://www.programiz.com/c-programming
Learning and Reference of C language.
Public Domain.
Also available in CC0 or MIT License.