Answers to the question above don't answer my question. I know what
extern
does. The question is if we ever needextern
. It only seems cleaner to useextern
(and compile with-fno-common
), but it doesn't seem there are situations when we need it.
Similar questions have already been answered (e.g. here), but this question is a bit different.
Say, I have two files:
file_a.c:
#include <stdio.h>
int sixsixsix = 666;
void lucky_seven();
int main(int argc, char *argv[]){
printf("%d\n", sixsixsix);
lucky_seven();
printf("%d\n", sixsixsix);
return 0;
}
file_b.c:
int sixsixsix;
void lucky_seven(){
sixsixsix = 777;
}
I can compile with GCC using gcc -std=c99 file_a.c file_b.c
with no errors. The compiled program gives as expected the output:
666
777
I only get errors if I compile with -fno-common
. In this case it is necessary to use extern
in file_b.c:
file_b.c:
extern int sixsixsix;
void lucky_seven(){
sixsixsix = 777;
}
Aside from this special case, that is, if I have a compiler which doesn't put multiply declared variables in a common block, is there any other use for extern
for variables? Can you give me example code in which extern
becomes unavoidable?