链接器无法分辨函数和变量之间的区别? [英] Linker is unable to tell the difference between function and variables?

查看:59
本文介绍了链接器无法分辨函数和变量之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码:

//Module 1
void sth()
{
}

//Module 2

int sth= 1;
int func()
{
}

,并且在调用 gcc 时,链接器会引发错误:

and when invoking gcc, the linker throws an error:

发现了sth的多个定义.

multiple definitions of sth found.

但是,链接是否愚蠢到无法分辨函数和变量之间的区别?特别是在ELF中有一个符号表,在其中有一个类型".在 Elf64_Symbol 中区分功能和对象.链接器为什么不使用此信息?

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?

推荐答案

您为链接程序指定了多个定义.

You gave multiple definitions to the linker.

符号 sth 在两个模块中定义,一个模块为 int ,一个模块为 void 函数.如果同一符号出现在多个对象文件中,而不论其类型如何,那么如果您尝试将它们链接在一起,则链接器将抛出错误.

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.

或者,如果希望特定符号仅在定义的文件中可见,而在其他符号中不可见,则需要向其中添加 static 存储类说明符.

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.

这篇关于链接器无法分辨函数和变量之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆