2

If I declare i to be a global variable twice, then it works fine:

#include <stdio.h>
int i;int i;
int main(void) 
{
    printf("%d",i);
    return 0;
}

But not if I declare it locally (twice)

#include <stdio.h>
int main(void) 
{
    int i;int i;
printf("%d",i);
return 0;
}

Error

error: redeclaration of ‘i’ with no linkage

Also, if in the 1st case I initialize i to some value i=1, then also it gives error error: redefinition of ‘i’

Why is does it exhibit such a behaviour ?

Thanks!

brokenfoot
  • 11,083
  • 10
  • 59
  • 80
  • 1
    It's a tentative definition. – devnull Mar 16 '14 at 18:03
  • @devnull: How does it impact what is being compiled? Why are these variables treated differently? – brokenfoot Mar 16 '14 at 18:06
  • 1
    @brokenfoot This is mostly a linker issue - files are compiled separately. Because it's the linker's job to "glue" the files together, tentative definitions make sense - but including an initializer "promotes" it to a definition (not a tentative definition). After all, it wouldn't make sense to have 2 different initializers for the same entity (and would be a maintenance nightmare). That's why it won't compile when you declare it with an initializer. – Filipe Gonçalves Mar 16 '14 at 18:08
  • Also refer to http://stackoverflow.com/questions/1433204/how-do-i-share-a-variable-between-source-files-in-c-with-extern-but-how – devnull Mar 16 '14 at 18:09
  • This one http://stackoverflow.com/q/21187163/2549281 is also on the same opic – Dabo Mar 16 '14 at 18:35

0 Answers0