我们使用 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;