Saturday, 7 September 2013

Variable access across multiple files

Variable access across multiple files

I was trying out programs based on extern and as i understand, this is
helpful when accessing variables across multiple files having only one
definition.
But i tried a simple program as below without "extern" and thing seem to
work when i expected it would fail during linking process
file5.c
1 #include <stdio.h>
2 #include "var.h"
3
4 int a = 20;
5
6 int main() {
7
8 printf("\n File5.c a = %d", a);
9 test();
10 return 0;
11 }
file6.c
1 #include <stdio.h>
2 #include "var.h"
3
4 int test() {
5 printf("\n File6.c a = %d",a);
6 }
7
var.h
int a;
As i have included "var.h" in all header files without extern, "int a"
would be included in both the .c file and during linking, compiler should
have thrown a warning or error message but it compiles file without any
issue. Shouldn't var.h have the following "extern int a"?

No comments:

Post a Comment