两个静态库,两个不同的向量实现,链接器会做什么? [英] Two static libs, two different vector implementations, what would the linker do?
问题描述
std :: vector
的不同实现构建的静态库。这两个二进制文件都具有 push_back
和 pop_back
的代码(因为向量通常是头文件)。当我们试图在项目中使用这两个库时,链接器会做什么。它会给一个错误吗?链接器可以删除每个方法的一个实现,以便可以进行以下操作: push_back
库调用 push_back
从第一个库执行
pop_back
从第一个库调用 pop_back
从第二个库执行
它会给一个错误吗?取决于你如何定义错误。
这可能不会在链接时给你一个错误。但它肯定会损坏你的可执行文件。当遇到符号的多个定义时,链接器假定,它们是相同的,因此除了其中一个之外的所有其他都可以被丢弃。如果他们不相同,你违反了单一定义规则,这意味着你走向未定义的行为土地。任何事情都可能发生。很可能,您会看到随机崩溃。
Imagine that we have two static libraries built with different implementations of std::vector
. Both of these binaries would have the code for both push_back
and pop_back
(since vector is usually header only). What would the linker do when we tried to use both of these libraries in a project. Would it give an error? Could the linker remove one implementation of each of these methods so that following is possible:
push_back
call from the second library calls push_back
implementation from the first library
pop_back
call from the first library calls pop_back
implementation from the second library
Would it give an error? Depends on how you define "error".
It probably would not give you an error at link-time. But it would certainly corrupt your executable. The linker assumes, when it encounters multiple definitions of a symbol, that they are identical, and so all but one of them can be discarded. If they're not identical, you're violating the One-Definition Rule, which means you're heading into Undefined Behavior-land. Anything might happen. Most likely, you'll see random crashes.
这篇关于两个静态库,两个不同的向量实现,链接器会做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!