I think what you’re talking about is a family of optimizations called “dead code elimination”, where machine code that is determined not to be reachable is stipped out of the program (or dynamic library). See Dead-code elimination - Wikipedia
If you’re curious how C++ compilers and linkers work there is a good site called Compiler Explorer at https://godbolt.org where you can enter some C++ code and see what the actual machine code output is. It’s generally considered a good idea for a programmer to study this topic (at least a little).