我可以在不同的 TU 中提供相同的功能定义吗

Could I provide same function definition in different TUs

我正在阅读有关内部和外部链接的内容,我发现默认情况下函数具有外部链接。

所以我在想是否可以在头文件管理器中声明一个函数并在不同的翻译单元中提供它的多个定义。

到目前为止我确实在头文件中声明了一个函数

void fct();

并在两个文件中提供 2 个定义,每个文件都包含在一个匿名命名空间中:

namespace
{
    void fct()
    {    
    }    
}

但我不明白这怎么可能是在不同 TU 中使用多个函数定义的好例子。

有人可以给我看一个简单的例子吗(甚至使用内联) 谢谢

Could I provide same function definition in different TUs

如果函数没有声明为内联,则否;这将违反单一定义规则。

可以在多个 TU 中定义具有外部链接的内联函数 - 额外要求定义必须相同。事实上,内联声明将强制在所有 TU 中提供 odr-use 函数的定义。

and provide 2 definitions in two files each of which is contained into an anonymous namespace:

这不违反标准规则。这两个函数不一样,也和全局的::fct.

不一样

But I didn't see how this could be a good examle of using multiple definitions of a function in different TU.

could someone show me a simple example of that (even using inline) thank you

给你:

// header.hpp
inline void foo() {}

// a.cpp
#include "header.hpp"

// b.cpp
#include "header.hpp"

这里有两个 TU,每个都包含函数 ::foo 的定义,来自同一个 header。这是允许的,因为该函数被声明为内联。


相关标准引述(当前草稿,无关细节由我编辑):

One-definition rule [basic.def.odr]

A ... function, ... shall not be defined where a prior definition is necessarily reachable ([module.reach]); no diagnostic is required if the prior declaration is in another translation unit.

...

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program outside of a discarded statement; no diagnostic required. ... A definition of an inline function or variable shall be reachable in every translation unit in which it is odr-used outside of a discarded statement.

...

There can be more than one definition of a ... inline function with external linkage ([dcl.inline]) ... in a program provided that no prior definition is necessarily reachable ([module.reach]) at the point where a definition appears, and provided the definitions satisfy the following requirements. ... no diagnostic is required unless a prior definition is reachable at a point where a later definition appears. Given such an entity named D defined in more than one translation unit, then

  • Each definition of D shall consist of the same sequence of tokens; and
  • ~ lenghy list of other limitations ~