Binary size: should we use static or dynamic linking?

submited by
Style Pass
2024-09-25 10:30:06

If at the end of a conference talk, I cannot answer a question and there is nobody to my rescue, I offer to reply later in the form of a blog post.

At C++ on Sea, someone asked me about the implications of dynamic linking concerning binary size. I hope I remember the question well! Let me phrase it differently: assuming the same code, what if you deliver an executable where libraries are dynamically linked and what if they are statically linked? How much bigger the dynamic version will be overall? Or maybe the static version will be larger?

In our original example, we compiled this into 5 different shared libraries and linked them together. Here are the commands I used on MacOS:

In order to calculate the full size of this example, we need to sum up the sizes of the shared objects and the main executable.

First, instead of compiling everything into a separate dynamic library, I compiled every translation unit (every .cpp file) into an object (.o) file. Then I used the ar command to create a different static library out of each object file.

Leave a Comment