Sunday, January 28, 2024

[SOLVED] Difference between -static and -static-libstdc++ in GCC

Issue

What other stuff does -static add to the final binary output that -static-libstdc++ does not add?

I checked the excellent answer for href="https://stackoverflow.com/questions/26103966/how-can-i-statically-link-standard-library-to-my-c-program">this question but it doesn't address this particular question that I have.

I tried the following program:

#include <iostream>


int main( )
{
    std::cout << "What does -static do that -static-libstdc++ doesn't do?\n";
}

Without any of these options specified for link-time, the generated output is only ~17 KB. However, by specifying -static-libstdc++ it becomes ~1.3 MB. And if -static is used instead, it becomes ~2.4 MB. What is being added by the -static flag that causes the latter two forms to have such a huge difference in size? And which things can be affected at runtime if only the -static-libstdc++ is specified at the linking stage?

Now which one is more suitable if someone wants to build a small program that can be run on Ubuntu (v18.04 and later)?


Solution

-static- implies -static-libgcc and -static-libstdc++ as well as that all other libraries are linked in, if possible, statically.

You can see what doesn't get in using ldd

Dependency resolution in Linux

$ g++ -static-libstdc++ -static-libgcc test.cpp
$ ldd a.out
        linux-vdso.so.1 (0x00007fff9a7a9000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f5122c90000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f5122fb7000)
$ g++ -static test.cpp
$ ldd a.out
        not a dynamic executable


Answered By - rogerdpack
Answer Checked By - Cary Denson (WPSolving Admin)