C++不使用匿名命名空间实现内部链接

C++ achieve internal linkage without using anonymous namespaces

我一直在阅读有关声明匿名名称空间以实现更短 linking-time 的内容。

但是,我了解到确实不建议在头文件中声明匿名命名空间:

When an unnamed namespace is defined in a header file, it can lead to surprising results. Due to default internal linkage, each translation unit will define its own unique instance of members of the unnamed namespace that are ODR-used within that translation unit. This can cause unexpected results, bloat the resulting executable, or inadvertently trigger undefined behavior due to one-definition rule (ODR) violations.

以上是摘自下面link的引述,其中有几个匿名命​​名空间意外行为的例子: https://wiki.sei.cmu.edu/confluence/display/cplusplus/DCL59-CPP.+Do+not+define+an+unnamed+namespace+in+a+header+file

所以,我的问题是:

上述问题仅适用于匿名命名空间变量,不适用于方法。是吗?

使用 static 关键字强制使用变量内部 linkage 时是否会出现同样的问题?如果是这样,是否有任何其他方法可以安全地实现这一目标?

The mentioned problems only applies to anonymous-namespace variables, not methods. Is that right?

提到的问题发生在 anonymous-namespace.

里面的任何东西上

Does the same problem appears when using static keyword for forcing internal linkage with variables?

同样的情况。

If so, is there any other way to achive this in a safety way?

没有。

如果您将任何具有内部链接(class、变量、成员函数、模板、 ETC...)。如果任何具有外部链接的实体在其定义或声明中使用这些具有内部链接的实体之一,您很快就会遇到问题。

在匿名命名空间内声明的任何实体,那些声明为 static 和 not-extern const 的变量具有内部链接。

有 2 个部分解决方案可以满足您的需求:

  • 内联变量和函数的定义可以出现在多个翻译单元中,因此在 header 个文件中定义它们是安全的。

  • 如果您正在寻找的不是让名称在您正在编写的库之外可见,请在私有 header 中定义它们并将可见性属性应用于它们([[gnu:visibility("hidden")]] 或 MSVC 没有 __dllexprot)