链接器实际上对乘法定义的内联函数有什么作用? [英] What do linkers actually do with multiply-defined `inline` functions?

查看:128
本文介绍了链接器实际上对乘法定义的内联函数有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C和C ++中,具有外部链接的inline函数当然可以在链接时具有多个定义,假设这些定义都是(希望)是相同的. (我当然是指用inline链接规范声明的函数,而不是编译器或链接时间优化器实际上内联的函数.)

In both C and C++, inline functions with external linkage can of course have multiple definitions available at link-time, the assumption being that these definitions are all (hopefully) identical. (I am of course referring to functions declared with the inline linkage specification, not to functions that the compiler or link-time-optimizer actually inlines.)

那么,常见的链接程序在遇到一个函数的多个定义时通常会做什么 ?特别是:

So what do common linkers typically do when they encounter multiple definitions of a function? In particular:

  • 最终的可执行文件或共享库中是否包含所有定义?
  • 该函数的所有调用是否都链接相同的定义?
  • 一个或多个C和C ++ ISO标准是否要求回答上述问题?如果不是,大多数通用平台会做同样的事情吗?

P.S.是的,我知道C和C ++是独立的语言,但是它们都支持inline,它们的编译器输出通常可以通过同一链接器链接(例如,GCC的ld),因此我认为它们之间没有任何区别在这方面.

P.S. Yes, I know C and C++ are separate languages, but they both support inline, and their compiler-output can typically be linked by the same linker (e.g. GCC's ld), so I believe there cannot be any difference between them in this aspect.

推荐答案

实际上,如果函数是内联的,则没有任何链接.仅出于任何原因,编译器决定内联扩展功能时,编译器必须生成该功能的脱机版本.如果编译器为一个以上的翻译单元生成该函数的离线版本,您最终将获得多个具有相同内联"函数定义的目标文件.

If the function is, in fact, inlined, then there's nothing to link. It's only when, for whatever reason, the compiler decides not to expand the function inline that it has to generate an out-of-line version of the function. If the compiler generates an out-of-line version of the function for more than one translation unit you end up with more than one object file having definitions for the same "inline" function.

将脱机定义编译到目标文件中,并对其进行了标记,以便链接器在该名称的定义不只一个时也不会抱怨.如果不止一个,则链接器仅选择一个.通常是它看到的第一个,但这不是必需的,并且如果定义都相同,那就没关系了.这就是为什么具有相同内联函数的两个或多个不同定义是未定义的行为的原因:没有选择哪个规则的规则.任何事情都可能发生.

The out-of-line definition gets compiled into the object file, and it's marked so that the linker won't complain if there is more than one definition of that name. If there is more than one, the linker simply picks one. Usually the first one it saw, but that's not required, and if the definitions are all the same, it doesn't matter. And that's why it's undefined behavior to have two or more different definitions of the same inline function: there's no rule for which one to pick. Anything can happen.

这篇关于链接器实际上对乘法定义的内联函数有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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