C - Keyword - Using extern

The extern keyword is designed to explicitely tells to someone seeing a variable in a code, that this variable has been firstly declared in another file.

So, even if you can choose to not use it, by convention and for a code more clear, you have to use it. 

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);


printf("#3 - global_var = %d\n", global_var);

global_var = 9;


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




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

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.