Search code examples
cvariablesexternvariable-declaration

Why variable var is not referenced?


This is not a problem to fix or something.Just want to know the behaviour

#include <stdio.h>
extern int var;
int main()
{
    var = 10;
    printf("%d ", var);
    return 0;
}

Here we can see that var was defined as extern and inside the main() function var was given definition. But when the var was outputted it gave an error

undefined reference to var.

Then where does the value 10 go? Will it go to extern var or it is stored in a garbage memory location?

So what exactly happens during compilation at line var =10 and the next line.

Compile Log:

Compilation error   time: 0 memory: 2156 signal:0
/home/PpnviQ/ccRtZapf.o: In function `main':
prog.c:(.text.startup+0x13): undefined reference to `var'
collect2: error: ld returned 1 exit status

Solution

  • In your code,

     extern int var;
    

    is a declaration, not a definition. So, in the complete translation unit, var is never defined. So your linker (to be specific) complains when you try to use it, (assign value to var).