Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Below is my code:

//Module 1
void sth()
{
}
//Module 2

int sth= 1;
int func()
{
}

and when invoking gcc, the linker throws an error:

multiple definitions of sth found.

But is the link that dumb that it couldn't tell the difference between functions and variables? Especially there is a symbols table in ELF, there is a "type" in Elf64_Symbol to differentiate function and object. Why doesn't the linker use this information?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
240 views
Welcome To Ask or Share your Answers For Others

1 Answer

You gave multiple definitions to the linker.

The symbol sth is defined in two modules, one as an int and one as a void function. If the same symbol appears in more than one object file, regardless of type, the linker will throw an error if you attempt to link those together.

A symbol can only be defined in one object file. If you want to use it in others you can declare it in the other file(s) however the declaration must match the definition.

Alternately, if you want a particular symbol to only be visible in the file it was defined in and not others, you need to add the static storage class specifier to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...