Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

c - Linker is unable to tell the difference between function and variables?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...