Reputation: 599
I have declared int x
in file one and by mistake I declared another variable of type char
with the same name x
in file two, and I wait the compiler or the linker to give me an error, but there are no errors displayed. and when I use the debugger I see that int x
is converted to char x
, is that true?! and what actually happens here?!
Show this modification on my code:
File One
#include <stdio.h>
int x = 50; /** declare global variable called
x **/
int main()
{
print();
printf(" global in file one = %d",x); /** Modification is just here **/
return 0;
}
File Two
char x;
void print(void)
{
x = 100;
printf("global in file two = %d ",x);
return;
}
My expected results are = global in file two = 100 global in file one = 50
but The results are : global in file two = 100 global in file one = 100
When I use the debugger I see that int x
is converted to char x
, is that true?! and what actually happens here?
Upvotes: 5
Views: 155
Reputation: 224884
You're in troublesome territory here. Technically your program causes undefined behaviour. char x
is a tentative definition, since it doesn't have an initializer. That means the linker unifies it with the int x
in the other file at link time. It's a bit weird looking, since your two declarations have different types, but it appears to have successfully linked in your case. Anyway, you have only one x
, and luck is making it work the way you're seeing it (and little-endian architecture, probably).
If you want the two variables to be independent, make them static
, and they'll be restricted to the scope of their respective translation units.
Upvotes: 6