Search code examples
c++gcclddynamic-linking

Statically include libc in c++ program with gcc without using -static option


I am trying to build a small c++ program with the least amount of dynamic dependencies as possible. The problem i am facing is that the program I am trying to build has a dynamic dependency with libmariadbcpp (which cannot be statically linked).

I.e. using -static option in compile command cause the compilation to fail, with error

/usr/bin/ld: attempted static link of dynamic object `/usr/local/lib/../lib/libmariadbcpp.so'

Currently the program builds by using the command

gcc main.cpp -o main -lmariadbcpp

But running ldd on main shows dependencies with libc.so.6, libm.so.6 and others...

Obviously the command

gcc main.cpp -o main -lmariadbcpp -static

does not work because -static overrides -lmariadbcpp but "logically" resemble what i would like to achieve.

I tried using -static-libstdc++ but there was no visible effect on produced binary (libc and libm were still listed by ldd).

Is there a way for me to statically compile my program such that no dynamic dependencies are listed by ldd except for libmariadbcpp?

Bonus question: where are options such as -static-libstdc++ defined? I tried looking for them by using --help with gcc and ld but to no avail.

Thank you very much!

Some additional info:

The issue i was trying to solve in a more broader sense is that the servers on which i work each has a different os distribution/version, and code compiled on my computer with dynamic dependencies fails to execute remotely (with errors such as /lib/x86_64-linux-gnu/libc.so.6: version GLIBC_2.34 not found).

Currently i am either re-compiling the programs on each server or wrapping them in docker containers, but this is not very practical so i thought removing dynamic dependencies was the way to go.


Solution

  • Is there a way for me to statically compile my program such that no dynamic dependencies are listed by ldd except for libmariadbcpp?

    No.

    If you are using any shared library at all, then you must also use ld-linux.so and libc.so.

    In fact, running ldd /usr/local/lib/libmariadbcpp.so will show both libc.so.6 and ld-linux, so your main will always have these dependencies no matter what.

    Bonus question: where are options such as -static-libstdc++ defined?

    In the GCC manual.

    P.S. http://xyproblem.info may be relevant here.