如何静态链接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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,434评论 0 10
  • 六点自然醒了。六点半出来客厅看到婆婆已经在炒饭了,还煮了饺子。突然间好感动,婆婆给我们到了两年半孩子了,虽然有不少...
    小云_6552阅读 217评论 1 1
  • 诺贝尔经济学奖得主、美国著名心理学家卡尼曼发现,人们对体验的记忆由两个因素决定:一个是高峰时的感觉,无论是正向的还...
    任性的Cissy阅读 405评论 0 0
  • 前两天突然看到B站上剪辑的关于欧美男星的混剪,看到伊桑·霍克,就忍不住向你们推荐这部《千钧一发》。 该片还有个别名...
    麻婆电影阅读 489评论 0 0
  • 四月初,和三水约好了五一黄金周出去旅游,他强烈推荐了凤凰古城。想着我对那里仰慕已久,还真没去过,便欣然应下了。听他...
    三石宝宝阅读 1,052评论 2 3