2

What is the practical use of extern in C? Wouldn't a global variable work the same when used across multiple files?

File head.h

int i;

This is included across multiple files and works as expected. Then what is the appropriate use of an extern ?

  • 2
    one reason that if you are using some library it gives more readability to you program. you would declare `extern int i; `in your program. This makes it clear that you are using a variable i which is not declared here. – Adi Oct 02 '15 at 17:01
  • https://stackoverflow.com/questions/496448/how-to-correctly-use-the-extern-keyword-in-c#comments-499330 – Cong Ma Oct 02 '15 at 17:04

2 Answers2

3

extern declares a global variable (usually in a header file). It should be defined in exactly one source file. Otherwise, depending on how smart your linker is, you might end up with an error or multiple definitions of the same variable. A modern linker will likely sort this out for you, though.

Hellmar Becker
  • 2,824
  • 12
  • 18
1

You can use extern to access Variables in different files...

e.g. see this:

file1.c

// Integer with external binding
int global1 = 10;
// REFERENCE to an external defined variable defined in file2.c
extern int global2;
// Integer with internal binding (not accessible with extern from other files)
static int internal1 = 20;

void print1() {
    printf("%d, %d, %d", global1, global2, internal);
}

file2.c

// REFERENCE to an external defined variable defined in file1.c
extern int global1;  

// Integer with external binding
int global2 = 20;

void print2() {
    // you wont be able to reach internal1 here! Even with extern!
    printf("%d, %d", global1, global2);
}

You see, the external keyword tells the compiler that the global variable exists, but in another file. You can reference variables declared somewhere else (e.g. in an external library or another object file. Its linker stuff). Also it will highly increase readability of your sourcecode and helps to avoid same-name variables! Its good practice to use it...

And btw: Global variables are per-default extern. Adding static changes them to internal variables!

Nidhoegger
  • 4,973
  • 4
  • 36
  • 81