简体   繁体   English

为什么 boost lib 有外部链接,而不是内部链接? (仅标题链接的最佳实践)

[英]Why does the boost lib have external linkage, not internal? (Best practice of linkage for header-only)

Boost library defines functions as following style ; Boost 库将函数定义为以下样式

namespace boost::io::detail {
    template<class Iter, class Facet>
    Iter wrap_scan_notdigit(...) {
        // snip
    }
}

To my understanding, the function has external linkage because据我了解,function 具有外部链接,因为

  • the namespace is on the global scope, not unnamed命名空间在全局 scope 上,未命名
  • function is not "static" declared function 未声明为“静态”

From my experience, the external linkage on the header often causes the ODR violation.根据我的经验,header 上的外部链接经常会导致 ODR 违规。 For example, two different translation units could include the different versions;例如,两个不同的翻译单元可能包含不同的版本; this often happens when you use 3rd-party当您使用 3rd-party 时,通常会发生这种情况.so 。所以.a (static) libs. .a(静态)库。

The critical issue of the ODR violation is NDR: compiler/linker doesn't have to emit errors, but it could generate an execution-time bug in the rare case. ODR 违规的关键问题是 NDR:编译器/链接器不必发出错误,但在极少数情况下它可能会生成执行时错误。

The internal linkage can avoid the problem.内部联动可以避免这个问题。

So my question is (same as on the title):所以我的问题是(与标题相同):

  • Why is the boost's linkage external, not internal?为什么boost的链接是外部的,而不是内部的?
  • (To be generalized above) How should I set the linkage for my header-only library? (上面概括)我应该如何为我的仅标题库设置链接?

the external linkage on the header often causes the ODR violation. header 上的外部链接经常导致 ODR 违规。

Only when the headers are poorly written (or possibly when they are poorly used, if definitions depend on preprocessor directives).仅当标头写得不好时(或者如果定义依赖于预处理器指令,则可能在使用不当时)。

External linkage reduces code bloat, as you need only one copy of each function per program, rather than one copy per translation unit.外部链接减少了代码膨胀,因为每个程序只需要每个 function 的一个副本,而不是每个翻译单元一个副本。

this often happens when you use 3rd-party.so libs.当您使用 3rd-party.so 库时,通常会发生这种情况。

Library object code should not export symbols from header-only libraries.库 object 代码不应从仅标头库中导出符号。 The point of header-only is that it is available without linking to library object code.仅标头的要点是它无需链接到库 object 代码即可使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM