0

I have a bit confusion about the variable definition and declaration using "extern" keyword. Assuming I want a variable 'timer' can be used in multiple c files. Then I can:

On c1.h

int timer;

Then on c1.c

#include "c1.h"
void timer_increase() {
    timer++
}

Then on c2.c

#include "c1.h"
void print_timer() {
    printf("%d", timer);
}

However, when I using extern variable:

On c1.h

extern int timer;

Then on c1.c

#include "c1.h"
int timer;
void timer_increase() {
    timer++
}

Then on c2.c

#include "c1.h"
void print_timer() {
    printf("%d", timer);
}

Both scripts work fine and I cannot see any reason that I have to used extern to declare a variable. Can anyone gives me any hints?

  • 1
    There are no scripts in C. All your code samples are programs. You also have a missing semicolon in `c1.c`. – DYZ Jun 15 '18 at 02:43
  • Please read this answer by [Storyteller](https://stackoverflow.com/a/49511662/918959). Basically that your program works is because the C implementation is using the common extension J.5.11, but your code is not strictly-conforming. Not all implementations do support J.5.11 - for example the Visual C++'s C compiler does not. – Antti Haapala -- Слава Україні Jun 15 '18 at 06:08

1 Answers1

0

You have to define the variable once and declare it in header so that rest of the files have visibility to the variable.

When you don't use extern in the header file, everytime you are defining the same variable in multiple files.

Gopi
  • 19,784
  • 4
  • 24
  • 36