Two static libraries, two different vector implementations, what would the linker do?

advertisements

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.