c++ - 链接器通常会优化掉来自不同 C++ 模板实例的重复代码吗?

标签 c++ templates linker instance multiple-instances

我使用 C++ 编程已经有一段时间了,我非常喜欢使用模板。由于我涉足嵌入式编程,我最近一直想知道的是,在模板参数不同的模板实例中,链接器应该如何处理代码重复。

对于具有相同参数的同一模板的多个实例,众所周知,这会在链接时被优化掉(另请参阅:How does C++ link template instances)

但是在我的例子中,我感兴趣的是链接器是否会识别两个模板之间的任何重复代码,这些模板是用不同的参数实例化的。由于它们是不同的类型,我假设它们不会自动折叠。然而,由于它们可能有一些不依赖于模板参数的函数,因此这两个类之间是相同的,因此我们可能会假设链接器可以优化这些函数,从而节省空间。

在这种情况下预期的行为是什么?

最佳答案

gold 链接器正是这样做的。

Safe ICF: Pointer Safe and Unwinding Aware Identical Code Folding in Gold :

We have found that large C++ applications and shared libraries tend to have many functions whose code is identical with another function. As much as 10% of the code could theoretically be eliminated by merging such identical functions into a single copy. This optimization, Identical Code Folding (ICF), has been implemented in the gold linker. At link time, ICF detects functions with identical object code and merges them into a single copy.

关于c++ - 链接器通常会优化掉来自不同 C++ 模板实例的重复代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38662972/

相关文章:

C++ 单构造函数模板特化

c++ - 为什么gcc从这里的回调函数的最后一个参数推断类型?

math - 编译和链接 KISSFFT

c++ - ncurses:奇怪的行格式

c++ - boost static_vector 而不是 std::is_trivially_destructible

c++ - 创建一个可以像 Vector of Vectors 一样工作的 C++ 模板类

architecture - vDSO:为什么 linux 只将它们用于与时间相关的功能?

c - 在特定内存中定位c库函数

c++ - SDL_VIDEORESIZE 事件中的奇怪高度值

c++ - C++中带负数的模