为什么内联函数默认有外部链接? [英] Why do inline functions have external linkage by default?

查看:480
本文介绍了为什么内联函数默认有外部链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准说,给定声明

inline void foo();

foo inline函数与外部链接(因为默认情况下所有函数声明都具有外部链接)。这让我很奇怪。因为一个定义规则部分3.2(在C ++ 03和C ++ 11中)说:

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 ...函数应在每个使用它的翻译单元中定义。

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

5可以有一个以上的定义[...] (7.1.2)...给定在多个翻译单元中定义的名为D的实体... D的每个定义将由相同的令牌序列组成

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

这意味着内联函数可能具有内部链接,因为通过外部链接(即跨翻译单元)以任何方式使用函数将是调用未定义的行为3),并且所有翻译单元中的内联函数的内容必须相同。

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.

这个规则有向后兼容性或特定工具链原因吗? / p>

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

推荐答案

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

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.

这篇关于为什么内联函数默认有外部链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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