/*main.c*/
#include<stdio.h>
extern void func(void);
main()
{
extern int i;
printf("i in main %d\n",i);
printf("Call to func before modifying i in main...\n");
func();
i=66;
printf("Call to func after modifying i in main to 66..\n");
func();
getchar();
}

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

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

The extern keyword only tells the compiler that the variable will be declared later. It's common to declare variables using extern in header files. Then in one, and only one *.c file the variable(s) have to be declared again but without the extern keyword.

The compiler does not complain about the difference between int and char in your program most likely because data type char is an integer -- but only one byte. So int and char are really both integers.

/*main.c*/
extern int f(void);
main()
{
f();
getchar();

}

/*file1.c*/
double *f()
{
printf("i am function returning a pointer to double");       
}

Output:

i am function returning a pointer to double.

Well, I agree char and int are interchangeable in most of the contexts but, the point here is although the compiler is unaware of the definition of extern function, how about the linker knowing it and raising an error? Is it only the 'name' that matters? signature of object(func or variable) during declaration(extern) and during definition can be different provided name is same?

Is it something thats undefined in standard ANSI and left to at the will of compilers?

That problem might be your compiler. vc++ 2010 express gives this warning, which is why I never let warning slide because they are normally actual errors.

error C2040: 'f' : 'double *()' differs in levels of indirection from 'int (void)'

I ran it on Devc++ 4.9.9.2. I'll cross check with other c-compiler.
It just got me scared about the robustness of c seeing this particular behaviour.
Thank you

with that compiler, as well as g++ and gcc, I think you have to add -Wall so that it will produce better warnings.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.