开发者

Multiple declarations and definitions

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 = 1开发者_如何学C0; 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.


Because there is a difference between a declaration and a definition. int i; does nothing more than introducing a name. int i = 10; on the other hand defines i, hence, a place in the memory must be reserved to store the value it corresponds to. But it is impossible for the compiler to know which value corresponds to i as you want to associate two memory locations with the name i.

This is under the assumption that you link these files against eachother, which is not entirely clear from your explanation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜