0%

Static link C++ library in GCC/CLANG

有些時候,我們不想要有libstdc++.so的相依性,而只要依賴libc,如果要整個重寫原先的C++ Code花費太大。

1
2
3
4
5
6
#include <iostream>
int main()
{
std::cout << "Hello" << std::endl;
return 0;
}

看一下相依性

1
2
3
4
5
6
7
8
$ g++ test.cpp -o test
$ ldd ./test
linux-vdso.so.1 => (0x00007fff184de000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f9cfb9b9000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9cfb5f4000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f9cfb2ee000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9cfbcbd000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f9cfb0d8000)

但是如果我們這樣坐的話,一切就會不同

1
2
3
4
5
6
7
8
$ g++ test.cpp -o test  -static-libstdc++ -static-libgcc
$ ldd ./test
linux-vdso.so.1 => (0x00007ffee379d000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f72ef99e000)
/lib64/ld-linux-x86-64.so.2 (0x00007f72efd63000)
$ g++ test.cpp -o test -static
$ ldd ./test
not a dynamic executable

這邊有三個選項
-static-libstdc++ 連結libstdc++.a
-static-libgcc 連結libgcc.a,如果只有-static-libgcc而沒有-static-libstdc++不起作用,但是反過來不是那麼一回事。
– ‘-static’ 去存所有相依性

Reference

How to Statically Link C and C++ Programs on Linux with gcc