The extern keyword is designed to explicitely tells someone, being watching a variable in a code, that this variable has been firstly declared in another file.
The extern keyword works also with C++.
Let's take an example.
	In the code below, I use 2 files.
	The first main.c where I declared the global_var variable.
	And file1.c where I redeclared it as an extern variable.
So we can see that I can change the value of this variable from both files.
/* main.c */
#include <stdio.h>
int global_var;
int     main()
{
  printf("#1 - global_var = %d\n", global_var);
  global_var = 1;
  printf("#2 - global_var = %d\n", global_var);
  modifVar();
  printf("#3 - global_var = %d\n", global_var);
  global_var = 9;
  displayVar();
  printf("#5 - global_var = %d\n", global_var);
  return 0;
}
/* file1.c */
#include <stdio.h>
extern int global_var;
void modifVar()
{
  global_var = 3;
}
void displayVar()
{
  printf("#4 - global_var = %d\n", global_var);
}#1 - global_var = 0 #2 - global_var = 1 #3 - global_var = 3 #4 - global_var = 9 #5 - global_var = 9
Comments
soru (not verified)
Wednesday, January 30, 2019 - 9:24am
Permalink
do we need to #include one
do we need to #include one file in another or will it work if both source files are in the same folder?
wachira anjana ... (not verified)
Wednesday, August 14, 2019 - 7:08am
Permalink
no need, compiler will do it
no need, compiler will do it for you.
Add new comment