0

Global value is not accessible in another file?Mycode is below please help me to fix

flie1.c

 #include<stdio.h>
 extern int i=9;  
  int main()
 {
   printf("i m in main\n");
 }

file2.c

  printf("%d\n",i);

i am compiling both file at once as cc file1.c file2.c

2 Answers2

0

Change it like this, and it will work:

file1.c

#include <stdio.h>
int i = 9; // define the variable
void print(); // declare print: say there is a function called `print` with no arguments and no return type (because the function is DEFINED in file2.c)

int main() {
     printf("im in main");
     print();
     return 0;
}

file2.c

extern int i; // declare "i": say there is a variable called `i` with type of `int` (because the variable is DEFINED in file1.c)

void print() { 
     printf("%d\n", i);
}
Marco
  • 7,007
  • 2
  • 19
  • 49
0

When you have an extern variable, it should also have its 'original' declaration (without using extern). extern simply says ' this variable is defined elsewhere', so you need to define the variable somewhere.

Simply add:

int i=9;

to file2.c (in the top of the file, the 'globals' area')

and you can change your extern declaration to:

extern int i;

(without the assignment of the value 9) in file1.c

Grantly
  • 2,546
  • 2
  • 21
  • 31