I am trying to understand extern. According to one of the top answers to How to correctly use the extern keyword in C
it's in order to solve the problem of multiple inclusions of a header file resulting in multiple copies of the same variable and thus leading to, presumably, a linking error.
So I tried it by creating the following files:
count.h
int count;
count.c
int count = 0;
add.h
int sum(int x, int y);
add.c
#include "count.h"
int sum(int x, int y){
count = count + 1;
return x+y;}
sub.h
int sub(int x, int y);
sub.c
#include "count.h"
int sub(int x, int y){
count = count + 1;
return x - y;
}
main.c
#include "count.h"
#include "add.h"
#include "sub.h"
#include <stdio.h>
int main(){
printf("%d\n", count);
printf("%d\n", sub(100,1));
printf("%d\n", count);
printf("%d\n", add(100,1));
printf("%d\n", count);
}
This compiles and runs fine with output:
0
99
1
101
2
I get the same output with or without extern in the original count.h file. So what am I missing in the answer?
Now, I thought the answer is that "I'm just declaring multiple copies of count" since there are no header guards, and that is OK because multiple declarations are OK, whereas multiple definitions are not. But then if that's the case, I would expect the following to compile, but it does not since I am "redefining count."
int main(){
int count;
int count;
int count = 0;
}
According to this answer, int count does count as a definition. In C, is it valid to declare a variable multiple times?