Extern reference to a variable name of different type

[code]
/*main.c*/
#include
extern void func(void);
main()
{
extern int i;
printf("i in main %d
",i);
printf("Call to func before modifying i in main...
");
func();
i=66;
printf("Call to func after modifying i in main to 66..
");
func();
getchar();
}

/*file1.c*/
char i=65;
void func(void)
{
printf("i in func %c
",i);
}

[/code]

OUTPUT:
i in main 65
Call to func before modifying i in main...
i in func A
Call to func after modifying i in main to 66..
i in func B

Question:
Why 'i' in main and file1 referring to same object? Why doesnt it give a link error saying undefined reference to 'i' as the types are conflicting though names are same.

If char i in were present in main itself, one would get complile error saying conflicting names.

Looking for a right explanation.

Thanks
Swapna


Comments

  • [color=Blue]Most likely it is an effect of bad quality compiler. What compiler did you use?[/color]
  • gcc for Dev c++
  • [color=Blue]I tried it on Visual Studio 2005 - results are below:[/color]
    [code]
    1>------ Build started: Project: junk89374, Configuration: Debug Win32 ------
    1>Compiling...
    1>junk89374.cpp
    1>Linking...
    1>junk89374.obj : error LNK2001: unresolved external symbol "int i" (?i@@3HA)
    1>D:Tempjunk89374Debugjunk89374.exe : fatal error LNK1120: 1 unresolved externals
    1>junk89374 - 2 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
    [/code]
    [color=Blue]
    When I fix main file as:
    [/color]
    [code]extern char i;[/code]
    [color=Blue]
    all builds fine.

    As I said a lot of times before - GCC is not that great - get free VS 2010 Express Edition, but you need to download Win SDK too.[/color]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories