Search code examples
cclangstatic-linkingdynamic-linkinglibc

attempting to link libc statically with clang, ldd showing dynamic linking?


I'd like to compile a C program with system libraries (such as libc) linked statically, with all my other custom libraries (such as openssl) linked dynamically. When I compile a "Hello World" program in C with clang 10.0.0-4ubuntu1 on Ubuntu 20.04, I expect to see libc linked statically, however it's linked dynamically, and the linker adds on libgcc_s as well:

$ clang /lib/x86_64-linux-gnu/libc.a main.c -o main
$ ldd main
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
    /lib64/ld-linux-x86-64-so.2

Trying a different suggestion yields the same result:

$ clang -Wl,-Bstatic -lc -Wl,-Bdynamic main.c -o main
$ ldd main
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
    /lib64/ld-linux-x86-64-so.2

Compiling without attempting to static linking libc yields the same result, just without libgcc_s.so.1 linked:

$ clang main.c -o main
$ ldd main
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
    /lib64/ld-linux-x86-64-so.2

Now, research says that glibc, which I'm using, shouldn't be statically linked--apparently musl is better for that. But is the above behavior expected, linking libc statically but showing a dynamic link, while also adding on libgcc_s? Is it in fact, possible to link glibc statically regardless of recommendation?


Solution

  • As you mentioned:

    Now, research says that glibc, which I'm using, shouldn't be statically linked--apparently musl is better for that. But is the above behavior expected, linking libc statically but showing a dynamic link, while also adding on libgcc_s? Is it in fact, possible to link glibc statically regardless of recommendation?

    Because glibc is heavily dependent on dynamic linking and other dynamic-linked components, it is designed for dynamic linking. When you statically link glibc, it does not mean that the entire libc is embedded within your binary. I would recommend you can study other methods, such as using another libc implementation like musl, bundling a shared library with your application or using Docker and other container technology to ensure a consistent runtime environment.

    Hopefully this helps!