Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple declarations and definitions

Tags:

c

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.

like image 725
Pointer Avatar asked May 06 '26 22:05

Pointer


2 Answers

You may be interested in this question and the answers. Keywords: "tentative definition".

Tentative definitions in C99 and linking

like image 135
Pascal Cuoq Avatar answered May 09 '26 11:05

Pascal Cuoq


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.

like image 41
Andy Dent Avatar answered May 09 '26 11:05

Andy Dent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!