C - Keyword - Using extern

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

/* 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

/* file1.c */
#include <stdio.h>

extern int global_var;

void modifVar()
{
  global_var = 3;
}

void displayVar()
{
  printf("#4 - global_var = %d\n", global_var);
}
 
Result:
#1 - global_var = 0
#2 - global_var = 1
#3 - global_var = 3
#4 - global_var = 9
#5 - global_var = 9

 

 

Comments

Comment: 

do we need to #include one file in another or will it work if both source files are in the same folder?

Comment: 

no need, compiler will do it for you.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.