0
/*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

2
Contributors
5
Replies
7
Views
6 Years
Discussion Span
Last Post by Ancient Dragon
0

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.

Edited by Ancient Dragon: n/a

0
/*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?

Edited by mike_2000_17: Fixed formatting

0

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)'

Edited by Ancient Dragon: n/a

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.