Content of X.c:
int i;
main ()
{
fun ();
}
Content of Y.c:
int i;
fun ()
{
}
Why does these two files compile with no error ? (using GCC)
But if i use int i = 10; it prints a multiple definition error.
You may be interested in this question and the answers. Keywords: "tentative definition".
Tentative definitions in C99 and linking
Assuming you really want an independent variable called i in each of these two files, you need to prefix them with static in order to give them internal linkage.
static int i = 10;
If you want i to be the same variable in both files, so changes in one affect the other, use the answers you were given 3 hours ago when you asked a variant of the question. If it is to be shared, you need to define the variable in one place.
As to why it didn't cause an error without the init, I think that's because you weren't using the variable until it needed initializing and so the compiler ignored it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With