我們使用 go help buildmode 可以看到 go 可以以多種方式進行構建,默認使用靜態鏈接庫.

➜ src go help buildmode The 'go build' and 'go install' commands take a -buildmode argument which indicates which kind of object file is to be built. Currently supported values are: -buildmode=archive Build the listed non-main packages into .a files. Packages named main are ignored. -buildmode=c-archive Build the listed main package, plus all packages it imports, into a C archive file. The only callable symbols will be those functions exported using a cgo //export comment. Requires exactly one main package to be listed. -buildmode=c-shared Build the listed main package, plus all packages it imports, into a C shared library. The only callable symbols will be those functions exported using a cgo //export comment. Requires exactly one main package to be listed. -buildmode=default Listed main packages are built into executables and listed non-main packages are built into .a files (the default behavior). -buildmode=shared Combine all the listed non-main packages into a single shared library that will be used when building with the -linkshared option. Packages named main are ignored. -buildmode=exe Build the listed main packages and everything they import into executables. Packages not named main are ignored. -buildmode=pie Build the listed main packages and everything they import into position independent executables (PIE). Packages not named main are ignored. -buildmode=plugin Build the listed main packages, plus all packages that they import, into a Go plugin. Packages not named main are ignored.
在macos上我們使用shared 模式,但是顯示不支持,我們換成linux平台進行實驗:
➜ src go install -buildmode=shared yxpkg -buildmode=shared not supported on darwin/amd64
創建libstd.so 庫:
root@docker ~/go# go install -buildmode=shared std
創建yxpkg包的 so庫:
root@docker ~/go# go install -buildmode=shared -linkshared yxpkg
編譯 main.go 生成動態鏈接的可執行文件:
root@docker ~/g/src# go build -linkshared yaoxu.go
我們對比之前生成的靜態鏈接的可執行文件:發現其可執行文件大小,相差很大;
root@docker ~/g/src# ll total 1.9M -rwxr-xr-x. 1 root root 22K Aug 29 17:17 yaoxu* -rw-r--r--. 1 root root 87 Aug 29 16:57 yaoxu.go drwxr-xr-x. 2 root root 4.0K Aug 29 16:27 yxpkg/ -rwxr-xr-x. 1 root root 1.9M Aug 29 16:57 yx_static*
我們分別使用ldd 查看兩個文件:
可見,兩個文件一個是動態鏈接文件,一個是靜態鏈接文件。
其中需要注意的是,go進行動態鏈接編譯的時候,還是需要源代碼文件輔助編譯,我想主要是構建符號表的原因。
還有一些具體的細節,你可以配置自己的環境,自行進行測試;
編譯后的工作區的目錄結構如下:
其中,yxpkg 是包,yaoxu.go文件中使用到了 yxpkg包中的函數內容;
工作區代碼可以在如下連接中找到:https://github.com/yaowenxu/Workplace/tree/a8adb505ca5ad81c58ff51c49b7f4d3dabf68b2f/go
保持更新,如果對您有幫助,請關注 cnblogs.com/xuyaowen;