Why do we have two types of libraries in C / C ++?

There are static libraries, and then there are shared libraries. Wouldn't it be possible to have only the general ones and link them statically, if necessary?

Compiling once with -fPIC and once doesn't seem like a waste. I don't know many builds, but shouldn't it be possible to convert rellocatable code to static code orders faster than recompiling everything?

+5
source share
3 answers

This is partly a historical issue. Once there were only static libraries. They were statically linked to each binary system compiled by the system. However, this was a maintenance nightmare, among other things, requiring that all used packages be recompiled if the library was fixed or changed.

Then shared libraries were used to fix these problems. Now for your question, firstly, there are several significant optimizations that can occur in a statically linked library that cannot be performed on a dynamic one, so even if someone had to convert dynamic libraries to static ones, this would probably be less efficient than statically compiled code in the first place.

Secondly, most modern systems use exclusively shared libraries anyway, so the problem is not very big, things are compiled only once, like a shared library.

As an insignificant stretch, however, it is relevant, you can take a look at prelinking . A step that removes some of the initial overhead (although it still doesn't necessarily achieve the same performance as a static link) and allows software that is dynamically linked in libraries to run faster.

+6
source

Although theoretically it would be possible to post-process dynamic libraries into static ones, the complexity of such a task, especially its good, would be comparable to compiling from scratch. Obtaining the same result through post-processing as when performing a static build from scratch is probably more difficult than just creating it again, plus any tool for that that will carry its own maintenance burden. Why go for it when there is already a great way to achieve the same goal?

In addition, the creation of both static and shared libraries is by no means required. Even where you want to do this, the additional cost of this (should be) a fairly small part of the total development time.

+1
source

You should use static libraries if you want the executable file not to depend on any library. Basically, a library is "sent" to an executable file.

Of course, this is very situational, since most shared time libraries are the way to go.

0
source

Source: https://habr.com/ru/post/1239939/


All Articles