Golang 的靜態(tài)編譯

Go語言和C語言的一個(gè)很大的區(qū)別是,Go語言只靜態(tài)編譯,做個(gè)測(cè)試:

$ cat testc.c
#include <stdio.h>
int main( void )
{
    printf("hello world \n");
    return 0;
}
$ cat testgo.go 
package main
import "fmt"
func main (){
    fmt.Println("hello world")
}
$ gcc testc.c -o testc
$ go build testgo.go
$ ls -lh testc testgo
-rwxrwxr-x 1 oo2 oo2 8.2K Sep 25 10:39 testc
-rwxrwxr-x 1 oo2 oo2 2.0M Sep 25 10:39 testgo

一方面是Go語言編譯后的可執(zhí)行文件大小比C語言的大很多,
另一方面是C語言的可執(zhí)行文件需要依賴 glibc 動(dòng)態(tài)庫,
ldd命令可以看出來:

$ ldd testc
    linux-vdso.so.1 (0x00007ffd57bcd000)
    /lib/x86_64-linux-gnu/libc-2.27.so (0x00007fdd35e03000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fdd363f6000)
$ ldd testgo
    not a dynamic executable

或者直接刪除 glibc 動(dòng)態(tài)庫,C可執(zhí)行程序報(bào)錯(cuò),而Go的還能運(yùn)行:

$ ./testc
hello world 
$ ./testgo
hello world
$ ls -lh /lib/x86_64-linux-gnu/libc.so.6
lrwxrwxrwx 1 root root 12 Jun  4 17:25 /lib/x86_64-linux-gnu/libc.so.6 -> libc-2.27.so
$ sudo rm /lib/x86_64-linux-gnu/libc.so.6
$ ./testc 
./testc: error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory
$ ./testgo
hello world

這時(shí)候只有內(nèi)部命令可以運(yùn)行,外部命令,包括 ln 甚至最常用的 ls 命令也不能運(yùn)行了:

$ type ls
ls is aliased to `ls --color=auto'
$ ln -s /lib/x86_64-linux-gnu/libc-2.27.so /lib/x86_64-linux-gnu/libc.so.6
ln: error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory
$ ls
ls: error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory

設(shè)置好 LD_PRELOAD 環(huán)境變量之后,ln命令可以運(yùn)行,但是 sudo 仍然不能運(yùn)行

$ export LD_PRELOAD="/lib/x86_64-linux-gnu/libc-2.27.so"
$ ln -s /lib/x86_64-linux-gnu/libc-2.27.so /lib/x86_64-linux-gnu/libc.so.6
ln: failed to create symbolic link '/lib/x86_64-linux-gnu/libc.so.6': Permission denied
$ sudo ln -s /lib/x86_64-linux-gnu/libc-2.27.so /lib/x86_64-linux-gnu/libc.so.6
sudo: error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory

只能靠 root 用戶來重新創(chuàng)建軟連接了:

# export LD_PRELOAD="/lib/x86_64-linux-gnu/libc-2.27.so"
# ln -s /lib/x86_64-linux-gnu/libc-2.27.so /lib/x86_64-linux-gnu/libc.so.6

所以用sudorm文件要小心,還是用 root 比較好。如果沒有預(yù)先留一個(gè)打開的 root 終端,登錄都登不進(jìn)去。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容