如何静态链接C++标准库

应用场景

通常是你希望你的程序使用固定的C++库版本,而不希望与他人共享程序(比如:动态库加载)。使用了他人的特殊C++库版本可能会导致意外Crash

编译命令

g++ -static-libstdc++ main.cpp -o main
ldd 查看main,已经未链接libstdc++.so.6

linux-vdso.so.1 => (0x00007ffd367e2000)
/$LIB/libonion.so => /lib64/libonion.so (0x00007f5a3d7e7000)
libm.so.6 => /lib64/libm.so.6 (0x00007f5a3d3ce000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f5a3d1b8000)
libc.so.6 => /lib64/libc.so.6 (0x00007f5a3cdf6000)
/lib64/ld-linux-x86-64.so.2 (0x00007f5a3d6d0000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007f5a3cbf2000)

编译选项

-static-libstdc++:该编译选项在gcc 4.5版本加入,必须在4.5或以上的gcc版本上才可使用

When the g++ program is used to link a C++ program, it normally automatically links against libstdc++. If libstdc++ is available as a shared library, and the -static option is not used, then this links against the shared version of libstdc++. That is normally fine. However, it is sometimes useful to freeze the version of libstdc++ used by the program without going all the way to a fully static link. The -static-libstdc++ option directs the g++ driver to link libstdc++ statically, without necessarily linking other libraries statically.

参考

https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html

你可能感兴趣的:(如何静态链接C++标准库)