简体   繁体   English

链接器无法区分函数和变量?

[英]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:并且在调用gcc ,链接器会抛出错误:

multiple definitions of sth found.找到了 sth 的多种定义。

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.特别是ELF中有一个符号表, Elf64_Symbol有一个“类型”来区分函数和对象。 Why doesn't the linker use this information?为什么链接器不使用这些信息?

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.符号sth定义在两个模块中,一个是int ,另一个是void函数。 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.或者,如果您希望特定符号仅在定义它的文件中可见,而在其他文件中不可见,则需要向其添加static存储类说明符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM