0

I had read that if I want to use a global variable in another C file,I should precede the data type with the access specifier extern like that:

File One                             File Two
int x, y;                            extern int x, y;
char ch;                             extern char ch;
int main(void)                       void func22(void)
{                                     {
/* ... */                              x = y / 10;
}                                     }
void func1(void)                      void func23(void)
{                                     {
x = 123;                               y = 10;
}                                     }

and by mistake in file two I don't declare x, y as they are. I declared them as int x and int y and I wait the compiler to display an error of redefinition of variables x and y, but the code runs without any errors.

for example:

File One

#include <stdio.h>

int global = 1000;  /** declare global variable called 
                       global **/

int main(){

print();

return 0;
}

File Two

int global;   /** here I don't use the extern keyword **/

void print(void){

global = 100;

printf("\n global = %d",global);

return;

}

the result is : global = 100

The program is compiled and linked without any error

So my question is: Is extern specifier is redundant here ?!

Armia Wagdy
  • 567
  • 6
  • 22

1 Answers1

0

You are not getting any error because the compiler does not check the type nor the existence of the external variable. It is in the linking phase that the linker searches in the object files for a reference to a symbol named x (or y).

pNre
  • 5,376
  • 2
  • 22
  • 27
  • so is it a redundant here ?!! can u explain to me more about what the compiler do here ? – Armia Wagdy Sep 22 '13 at 14:40
  • It is not redundant, the `extern` keyword tells the compiler there's a symbol named `x` somewhere else then the linker searches for this symbol's definition in the objects files being linked. If there's no `extern` the symbols are redefined leading to a linking error (duplicate symbol named x) – pNre Sep 22 '13 at 14:44
  • but there is no linking error also! – Armia Wagdy Sep 22 '13 at 18:01