C++内部链接的实际应用

Real Applications of internal linkage in C++

这听起来像是 What is the point of internal linkage in C++ 的重复版本,很可能是。只有一个 post 包含一些看起来不像实际示例的代码。 C++ISO 草案说:

When a name has internal linkage, the entity it denotes can be referred to by names from other scopes in the same translation unit.

它对我来说看起来是一个很好的准时定义,但我找不到任何合理的应用,比如:“看这段代码,这里的内部链接对实现它有很大的不同”。此外,根据上面提供的定义,看起来全局变量履行了内部链接职责。你能提供一些例子吗?

内部链接是遵守One Definition Rule.

的实用方法

人们可能会发现需要使用普通名称定义函数或对象,例如 sumtotalcollection 或任何其他常用术语,超过一次。在不同的翻译单元中,它们可能服务于不同的目的,特定于特定翻译单元的特定目的。

如果只存在外部链接,您必须确保相同的名称不会在不同的翻译单元中重复,即 little_sumbig_sumred_sum 等...在某些时候,这会变得非常老,非常快。

内部联动解决了这个问题。 unnamed namespaces 有效地导致整个 类 和模板的内部链接。使用未命名的命名空间:如果翻译单元需要自己的私有小模板,使用实用名称 trampoline 它可以继续并安全地使用它,而不必担心违反 ODR。

考虑辅助函数,它们并不完全需要暴露在外部,例如:

// Foo.hh
void do_something();
// Foo.cc
static void log(std::string) { /* Log into foo.log */ }
void do_something() { /* Do stuff while using log() to log info */ }
// Bar.hh
void bar();
// Bar.cc
static void log(std::string) { /* Log into bar.log */ }
void bar() { /* Do stuff while using log */ }

您可以在项目的两个部分中使用正确的 log 函数,同时避免多个定义错误。

后一部分对于 header 仅库非常重要,其中库可能包含在同一项目的多个翻译单元中。

现在关于使用带有变量的内部 linkage 的原因:同样,您可以避免多个定义错误,这将是这样的代码的结果:

// Foo.cc
int a = 5;
// Bar.cc
int a = 5;

编译时,编译器会愉快地生成 object 代码,但 linker 不会 link 一起生成。