为什么内联函数默认有外部链接?

发布于 2025-01-06 01:38:02 字数 526 浏览 0 评论 0原文

声明

inline void foo();

该标准规定,给定的foo 是一个内联函数,外部链接(因为默认情况下所有函数声明都有外部链接)。这让我觉得很奇怪。因为单一定义规则第 3.2 节(在 C++03 和 C++11 中)说:

3 ...内联函数应在使用它的每个翻译单元中定义。

5 a[n] 可以有多个定义 ... 具有外部链接的内联函数 (7.1.2) ... 给定这样一个名为 D 的实体在多个翻译单元中定义 ... 每个定义D 应由相同的标记序列组成

这意味着内联函数也可能具有内部链接,因为通过外部链接(即跨翻译单元)以任何方式使用该函数都将调用未定义的行为(根据第 3 段) ,并且所有翻译单元中内联函数的内容都需要是一样的。

此规则是否存在向后兼容性或特定工具链原因?

The standard says that given a declaration of

inline void foo();

that foo is an inline function with external linkage (because by default all function declarations have external linkage). This strikes me as odd. because the one definition rule section 3.2 (in both C++03 and C++11) say:

3 ... An inline function shall be defined in every translation unit in which it is used.

5 There can be more than one definition of a[n] ... inline function with external linkage (7.1.2) ... Given such an entity named D defined in more than one translation unit ... each definition of D shall consist of the same sequence of tokens

This means that an inline function might as well have internal linkage, because use of the function in any way through external linkage (that is, across translation units) would be to invoke undefined behavior (by paragraph 3), and that the content of the inline function in all translation units needs to be the same.

Is there a backwards compatability or specific toolchain reason for this rule?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悸初 2025-01-13 01:38:02

该决定的一个结果是,在内联函数中定义的静态变量将在该函数的所有实例之间共享。如果默认是内部链接,则每个翻译单元都会获得自己的静态变量副本。这不是人们期望的工作方式 - 内联与非内联不应该如此彻底地影响代码语义。

One result of that decision is that a static variable defined within an inline function will be shared between all instantiations of the function. If the default had been internal linkage, each translation unit would have gotten its own copy of the static variable. That's not how people expect things to work - inline vs. non-inline shouldn't affect the code semantics so drastically.

好听的两个字的网名 2025-01-13 01:38:02

Jonathan Schilling 的文章在这里恰当地回答了这个问题:默认外部内联

引用他关于这一改变的动机:

这一变化的直接动机是同一次会议上通过的新模板编译模型的需要;但更普遍的是,人们认为更改默认值的时机已经到来,并且这一更改在 ANSI 和 ISO 中得到了一致批准。

This is aptly answered here by Jonathan Schilling's article: Extern Inlines By Default.

To quote him about motivation for this change:

The immediate motivation for this change was a need of the new template compilation model that was adopted at the same meeting; but more generally it was felt that changing the default was an idea whose time had come, and the change was approved unanimously in both ANSI and ISO.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文