2 ms·
Static linking does not have to waste any RAM by duplicating code, even if it is frequently implemented in this way. It is possible and not complicated to impl
by adrian_b 2y ago
Static linking does not have to waste any RAM by duplicating code, even if it is frequently implemented in this way.
It is possible and not complicated to implement static linking in a way where the executable file retains the metadata about the component object files and also the OS retains some information about the object files that are already loaded in memory as parts of other executables.
In this case, when loading an executable, the component objects that are already present in memory can be omitted and the references to them in the executable can be adjusted.
While this is not done in the more popular operating systems, due to their preference for the more inefficient dynamic linking, the alternative is still possible.
Moreover, it is impossible to say in general which of static linking and dynamic linking wastes more memory. Static linking will have multiple copies of some code, while dynamic linking will have a lot of unused unreachable code, which is superfluous. Moreover, dynamic linking also has some execution time overhead.
In practice, with the typical bloated dynamic libraries that are available, I have seen much more memory wasted by dynamic linking than by static linking.
When only static linking is used, there is rarely much code duplication besides a small subset of the standard C library, which includes things like the wrappers for system calls and the functions for formatted I/O.
Therefore most of the benefit in reducing memory use from dynamic linking would be achieved with a single dynamic library, which should contain only a subset of libc.